如何为DateTime比较字符串字符串、何为、DateTime

2023-09-03 20:59:34 作者:戀曲↑

我有字符串,其中包含一个时间(从DB获得):

 字符串user_time =十七点十分03秒; //小时:分钟:秒
日期时间TIME_NOW = DateTime.Now;
 

我如何比较这串为DateTime?我想是这样的:

 如果(TIME_NOW> user_time)
{
    //做一点事
}
其他
{
  //做一点事
}
 

解决方案

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

  VAR dateTimeStr =17点10分03秒;
VAR user_time = DateTime.Parse(dateTimeStr);
VAR TIME_NOW = DateTime.Now;

如果(TIME_NOW> user_time)
{
  //你的code ...
}
 
解决 从字符串转换为datetime时发生语法错误

记住,这比较日期/时间有时需要时区的认识,使比较有意义的。

I have string which contains a time (obtained from a DB):

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

How do I compare this string to a DateTime? I'd like something like this:

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

解决方案

DateTime supports comparison, but first you need to parse the date-time string, DateTime.Parse() should suffice:

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

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

Bear in mind, that comparing dates/times sometimes requires awareness of time-zones to make the comparison meaningful.