How to compare datetime with string

I have a line that contains the time (obtained from the database):

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

How to compare this string with DateTime? I would like something like this:

 if(time_now > user_time) { //Do something } else { //Do something } 
+4
source share
6 answers

DateTime supports comparison, but first you need to parse the date string, DateTime.Parse () should be enough:

 var dateTimeStr = "17:10:03"; var user_time = DateTime.Parse( dateTimeStr ); var time_now = DateTime.Now; if( time_now > user_time ) { // your code... } 

Remember that comparing dates / times sometimes requires awareness of time zones in order to make the comparison meaningful.

+14
source

The problem is that DateTime.Now includes the date, "17:10:03" does not. Do it like this:

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

Do everything in your power to convert this type of row column to datetime column.

+2
source

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

+1
source

DateTime.Parse Converts a string to a DateTime object, which can then be used for comparison.

+1
source
 if (DateTime.Now > DateTime.Parse(user_time)) { ... } 

But you really shouldn't store time as a string, you should use your own time or date format in your database, so you could use the time value in your queries and index them correctly.

+1
source
 if (time_now > Date.Parse(DBString)) { } else { } 
0
source

Source: https://habr.com/ru/post/1308184/


All Articles