Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to equal 2 date variable in c#

Tags:

c#

DateTime dt=Convert.ToDateTime(data);
    if ((dt.Year == DateTime.Now.Year) 
       && (dt.Month == DateTime.Now.Month) 
       && (dt.Day == DateTime.Now.Day))
    lblDate.Text = "Today";

This code too lazy

  1. How to compare 2 date variables the easy way?
  2. How to get the difference of 2 date variables in minutes?
like image 599
ebattulga Avatar asked Dec 02 '22 07:12

ebattulga


2 Answers

For the first question:

  • In general:

    if (first.Date == second.Date)
    
  • To check whether a DateTime is "today"

    if (dateTime.Date == DateTime.Today)
    

Note that this doesn't take any time zone issues into consideration... What do you want to happen if the other DateTime is in UTC, for example?

I'm not sure what you mean by the second question. Could you elaborate? You can do:

TimeSpan difference = first - second;

if that's any help... look at the TimeSpan documentation for more information about what's available. For instance, you may mean:

double minutes = (first - second).TotalMinutes;

but you may not...

like image 103
Jon Skeet Avatar answered Dec 06 '22 10:12

Jon Skeet


1. DateTime.Equals(DateTime dt1, DateTime dt2)
like image 40
grega g Avatar answered Dec 06 '22 10:12

grega g