tesicg
tesicg

Reputation: 4053

How to designate if some DateTime value is in the same day in C#?

For example there will be some event today at 20:30. We sold the tickets earlier that day. The tickets can be returned only in the same day.

Somebody wants to return the ticket today it doesn't matter if it's before or after event time, but it should be in that day.

How to designate if some DateTime value is in the same day in C#?

Upvotes: 1

Views: 815

Answers (5)

terrybozzio
terrybozzio

Reputation: 4542

you can do this(with the time of event checking added if by some case needed).

if ((DateVariable.Date == DateTime.Today) && (DateTime.Now.TimeOfDay < new TimeSpan(20,30,0))) 
{
    //your work here....
}

Upvotes: 1

Lucas
Lucas

Reputation: 894

You have to compare the properties of each DateTime.

For instance:

DateTime date1 = new DateTime(2013, 01, 01, 01, 00, 00); // Jan 1th, 2013 - 01:00 AM
DateTime date2 = new DateTime(2013, 01, 01, 02, 00, 00); // Jan 1th, 2013 - 02:00 AM

if (date1.Day == date2.Day && date1.Month == date2.Month && date1.Year == date2.Year)
{
    // Your code here.
}

Upvotes: -1

phil soady
phil soady

Reputation: 11328

MSDN docu of DateTime

DateTime date1 = new DateTime(2013, 6, 27, 7, 47, 0);
// Get date-only portion of date, without its time.
DateTime dateOnly = date1.Date;

if (Date1.Date == Date2.Date)
{ //lucky Day}
else 
{ // loser
 }

But if your building a new tool. Use DateTimeOffSet

See the Now and Today properties

Upvotes: 2

Microsoft DN
Microsoft DN

Reputation: 10020

if(yourEventDate == DateTime.Today)

will that work?

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500055

Something like:

if (ticket.Date == now.Date) // For some value of now

Or perhaps:

if (ticket.Date == DateTime.Today)

? You need to consider whether time zones could cause you a problem, too... You need to be aware that DateTime has some significant ambiguities - it's easy to avoid thinking about the things that you should really be paying attention to, particularly in terms of which time zone you're interested in.

EDIT: As noted in comments, you could indeed use Noda Time, at which point you'd want to compare LocalDate values - again, you still need to consider which time zone is relevant.

Upvotes: 7

Related Questions