You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从DataGridView的DateTime字符串中提取时间值?

解决方案:提取DateTime字符串中的时间部分

嗨,作为C#初学者碰到这种需求太常见啦!你现在的问题是已经有了一个包含日期和时间的字符串Column4,想要单独提取出时间部分(比如07:00:00),同时不影响DataGridView的显示,我给你两种靠谱的思路:

方法1:从源头上处理(推荐)

其实你一开始就没必要把DateTime直接转成完整字符串再去提取——先保留DateTime对象,后续需要完整格式给DataGridView,需要时间就单独提取,这样既灵活又不会出错:

// 先保留DateTime对象,而不是直接转成字符串
DateTime targetTime = DateTime.Today.AddDays(1).AddHours(7);

// 给DataGridView用的完整格式字符串(和你原来的Column4一样)
string column4ForDGV = targetTime.ToString();

// 提取时间部分的字符串,格式为HH:mm:ss
string timeOnly = targetTime.ToString("HH:mm:ss");

// 测试输出
Console.WriteLine(timeOnly); // 会输出 07:00:00

这种方法的好处是完全避免了字符串分割可能带来的格式问题,因为DateTime本身就包含时间信息,直接格式化输出就行。

方法2:从已有的Column4字符串中提取

如果因为某些原因你已经只有Column4这个字符串了,那可以先把它解析回DateTime对象,再提取时间:

string Column4 = DateTime.Today.AddDays(1).AddHours(7).ToString();

// 先把字符串解析为DateTime对象
if (DateTime.TryParse(Column4, out DateTime parsedTime))
{
    // 提取时间部分
    string timeOnly = parsedTime.ToString("HH:mm:ss");
    Console.WriteLine(timeOnly); // 输出 07:00:00
}
else
{
    // 处理解析失败的情况(不过你的场景里基本不会出现)
    Console.WriteLine("无法解析日期时间字符串");
}

或者如果你确定字符串的格式是固定的(比如日期和时间之间用空格分隔),也可以用字符串分割的方式,但这种方法不如解析DateTime靠谱,因为如果格式变了就会出错:

string Column4 = DateTime.Today.AddDays(1).AddHours(7).ToString();
// 按空格分割,取第二部分就是时间
string timeOnly = Column4.Split(' ')[1];
Console.WriteLine(timeOnly); // 输出 07:00:00

注意事项

  • 不管用哪种方法,DataGridView的显示都可以继续用原来的Column4,完全不会受影响;
  • 推荐用方法1,因为DateTime对象的操作比字符串操作更稳定,尤其是后续如果需要修改时间、比较时间之类的需求,都能轻松应对。

内容的提问来源于stack exchange,提问作者Logan9Fingers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:20:42