开发者

How to compare a DateTime to a string

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

开发者_如何学Cstring 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.


The problem is that DateTime.Now includes a date, "17:10:03" doesn't. Do it like this:

    Dim dbaseTime As TimeSpan = TimeSpan.Parse("17:10:03")
    If DateTime.Now.TimeOfDay > dbaseTime Then
        Console.WriteLine("Let's go home")
    End If

Do everything in your power to convert that string column type to a datetime column.


You can use DateTime.Compare() along with DateTime.Parse() to convert the string to a DateTime object.


DateTime.Parse Will convert the string into a DateTime object which you can then use to compare.


if (DateTime.Now > DateTime.Parse(user_time))
{
   ...
}

But you really shouldn't store a time as a string, you should use the native time or datetime format of your database, that way you could use the value of the time in your queries, and index them properly.


if (time_now > Date.Parse(DBString)) {

} else {

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜