MattoMK MattoMK - 3 months ago 14
C# Question

How to calculate start of day and end of day from a date in c#

I have a date coming into my c# program like this: "01/15/2015", and I need to translate that to a string like this: "2015-01-15T00:00:00Z" (i.e., the beginning of that day). I am calling a 3rd party api that expects that format.

Then I need to take the same date and convert it to this: "2015-01-15T23:59:59Z" (i.e., the end of the day given).

Here is what I have, which appears to work based on the limited testing I've done, but I am wondering if this is prone to errors or if there is a better way to accomplish this. I haven't worked with dates in this format before so I thought I'd ask those with more experience. Will T23:59:59Z be the end of the day in the time zone my server is on?

program example:

class Program
{
static void Main(string[] args)
{
Search("01/15/2015");
}

private static void Search(string date)
{
//produce this:
//string startOfDay = "2015-01-15T00:00:00Z";
//string endOfDay = "2015-01-15T23:59:59Z";

DateTime temp1 = DateTime.Parse(date);
string startOfDay = temp1.ToString("yyyy-MM-ddTHH:mm:ssK") + "Z";

DateTime temp2 = DateTime.Parse(date);
string endOfDay = temp2.ToString("yyyy-MM-ddT") + "23:59:59Z";
}
}

Win Win
Answer

Start of day is easy; you can just use .Date.

FYI: Please make sure you check culture.

enter image description here

class Program
{
    static void Main(string[] args)
    {

        DateTime date;
        if (DateTime.TryParse("01/15/2015", out date))
        {
            var startOfDay = date.Date;
            Console.WriteLine(startOfDay.ToString("s") + "Z");

            var endOfDay = date.ToEndOfDay();
            Console.WriteLine(endOfDay.ToString("s") + "Z");
        }

        Console.ReadLine();
    }
}

public static class DateExtensions
{
    public static DateTime ToEndOfDay(this DateTime date)
    {
        return date.Date.AddDays(1).AddTicks(-1);
    }
}