Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare a DateTime to a string

Tags:

c#

.net

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
}
like image 239
lolalola Avatar asked Apr 27 '10 20:04

lolalola


1 Answers

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.

like image 127
LBushkin Avatar answered Oct 06 '22 17:10

LBushkin