c# - 如何将 DateTime 与字符串进行比较

标签 c# .net datetime

我有一个包含时间的字符串(从数据库中获取):

string user_time = "17:10:03"; //Hours:minutes:seconds
DateTime time_now = DateTime.Now;

如何将此字符串与 DateTime 进行比较?我想要这样的东西:

if(time_now > user_time)
{
    //Do something
}
else
{
  //Do something
}

最佳答案

DateTime 支持比较,但首先需要解析日期时间字符串,DateTime.Parse()应该足够了:

var dateTimeStr = "17:10:03";
var user_time = DateTime.Parse( dateTimeStr );
var time_now = DateTime.Now;

if( time_now > user_time )
{
  // your code...
}

请记住,比较日期/时间有时需要了解时区才能使比较有意义。

关于c# - 如何将 DateTime 与字符串进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2725055/

相关文章:

c# - 使用多个线程在套接字中发送数据包

c# - GridView CSS 问题。如何将 CSS 添加到标题 tr

c# - 如何在AppDomain内的程序集中调用静态方法

c# - 结构体包装值类型并通过索引提供访问权限

javascript - 如何格式化数据表中显示的日期

c# - 使用 Youtube API 添加评论在 .NET 中随机失败

c# - 实现策略模式而不是几个 if 语句

c# - SharePoint 错误 : Web application at xxxx could not be found

c# - 在 C#/.NET 中逐笔更新到烛台/OHLC 数据

python - Django 时区如何工作?