Ian Jeff
Ian Jeff

Reputation: 25

C# Check given date and time

Good day everyone. I'm new to C# but I can't seem to understand how DateTime work. All I wanted to do is to check If a (givenday) = today and time is 7pm I wanted to return true. Is this the right way to do it?

Take note ActionDate is a field which is inputed by the user.

DateTime dateA = Convert.ToDateTime(ActionDate);

int a = dateA.Year;
int b = dateA.Month;
int c = dateA.Day;
int d = timeA.Hour;
int e = timeA.Minute;

var newDate = new DateTime(a, b, c, d, e, 0);

DateTime end = Convert.ToDateTime(newDate);
DateTime start = Convert.ToDateTime(A);

TimeSpan span = end.Subtract(start);
Decimal minutes = Convert.ToDecimal(span.TotalMinutes);

if 
{
return true;
} else
{
return false;
}

Thank you in advance.

Upvotes: 1

Views: 311

Answers (3)

Nino
Nino

Reputation: 7095

You have made your code a bit too complicated. First, convert that user input to date, and compate it with current date and time.

DateTime dateA = Convert.ToDateTime(ActionDate);
if (dateA.Date == DateTime.Today && dateA.Hour == 19)
{
    //it is current date and hour is 7pm
}

Alternatively, check if user's imput is ok, like this:

DateTime dateA;
if (!DateTime.TryParse(ActionDate, out dateA))
{
   //alert user that he's entered wrong date 
}

EDIT: as Tim Schmelter noted, code's a bit more readable using DateTime.Today instead of DateTime.Now.Date

Upvotes: 0

TheLethalCoder
TheLethalCoder

Reputation: 6744

The way to check if a give date is today and is at 7pm is to use DateTime.Now.

Note that 19 is 7pm and 7 is 7am, the Hour property uses 24 hour format.

bool IsCurrentDayAnd7(DateTime dt) => dt.Date == DateTime.Now.Date && dt.Hour == 19;

As @TimSchmelter commented you could use DateTime.Today:

bool IsCurrentDayAnd7(DateTime dt) => dt.Date == DateTime.Today && dt.Hour == 19;

Upvotes: 1

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14604

You can use Date property to compare date with current date.

if (newDate.Date == DateTime.Now.Date && newDate.Hour == 19)
{
 return true;
}

Upvotes: 0

Related Questions