Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the start and end times of a day

Tags:

c#

datetime

In my C# app, I pass a string variable that is of format yyyymmdd-yyyymmdd that represents a from and to date. I want to get the start and end times for these dates respectively. Currently I have the below code but was wondering if there was more of an elegant solution?

So for pdr = 20090521-20090523 would get "20090521 00:00:00" and "20090523 23:59:59"

private void ValidateDatePeriod(string pdr, out DateTime startDate,                                  out DateTime endDate) {     string[] dates = pdr.Split('-');      if (dates.Length != 2)     {         throw new Exception("Date period is of incorrect format");     }      if (dates[0].Length != 8 || dates[1].Length != 8)     {         throw new Exception("Split date periods are of incorrect format");     }      startDate = DateTime.ParseExact(dates[0] + " 00:00:00",          "yyyyMMdd HH:mm:ss", null);     endDate = DateTime.ParseExact(dates[1] + "23:59:59",          "yyyyMMdd HH::mm:ss", null); } 
like image 764
David Avatar asked May 24 '09 00:05

David


People also ask

How do you get start time and end of day?

ZonedDateTime zdtStart = zdt. toLocalDate(). atStartOfDay( zoneId ); Using Half-Open approach, get first moment of following day.

How do you get the day start time?

Use the setUTCHours() method to get the start and end of the day, e.g. startOfDay. setUTCHours(0, 0, 0, 0) . The method takes the hours, minutes, seconds and milliseconds as parameters and sets them for the specified date according to universal time.


1 Answers

I am surprised to see how an incorrect answer received so many upvotes:

Wrong value

The correct version would be as follows:

public static DateTime StartOfDay(this DateTime theDate) {     return theDate.Date; }  public static DateTime EndOfDay(this DateTime theDate) {     return theDate.Date.AddDays(1).AddTicks(-1); } 
like image 75
anar khalilov Avatar answered Sep 28 '22 17:09

anar khalilov