onkami
onkami

Reputation: 9411

How to get "today's local midnight expressed in UTC" using .NET core?

I am trying to get a timestamp for "Local midnight in UTC" using .NET Core.

I wrote this code:

var utcTimeStartLocalDay =
            TimeZoneInfo.ConvertTimeToUtc(convertToLocalTimezone(DateTime.UtcNow).Date);

where

public DateTime ConvertToLocalTimezone(DateTime dateTime)
{
    return TimeZoneInfo.ConvertTime(dateTime, TimeZoneInfo.Utc,TimeZoneInfo.FindSystemTimeZoneById("FLE Standard Time"));
}

So, the idea is to get Utc timestamp, convert it to local TZ, then take Date (that is, discard time part and effectively make a midnight timestamp) and convert back to Utc - that should have given me local time.

However, it did not happen, as the result of the first expression is Utc midnight when printed.

Fiddle: https://dotnetfiddle.net/wJIXve

What do I need to correct here to get as the answer the local midnight for the day expressed as UTC (something like 22:00 UTC previous day)?

Edit: just to clarify an unclearness in the question: by "local" TZ I meant known local timezone (found in the code)

Upvotes: 1

Views: 2226

Answers (3)

David Specht
David Specht

Reputation: 9074

This should work.

var result = DateTime.Now.Date.ToUniversalTime();

Upvotes: 3

TheHvidsten
TheHvidsten

Reputation: 4428

To ensure that you are definitely using local time, I would use this code:

DateTime localMidnight = DateTime.SpecifyKind(DateTime.Now.Date, DateTimeKind.Local);

Then simply use .ToUniversalTime() to get the UTC date:

DateTime localMidnightUtc = localMidnight.ToUniversalTime();

Here's a working example:

static async Task Main(string[] args)
{
    DateTime localMidnight = DateTime.SpecifyKind(DateTime.Now.Date, DateTimeKind.Local);
    DateTime localMidnightUtc = localMidnight.ToUniversalTime();

    Console.WriteLine($"localMidnight:    {localMidnight}");
    Console.WriteLine($"localMidnightUTC: {localMidnightUtc}");
}

// Output:
// localMidnight:    29.01.2020 00:00:00
// localMidnightUTC: 28.01.2020 23:00:00

(And now you know which timezone I'm in ;)

Upvotes: 3

Steve Danner
Steve Danner

Reputation: 22158

This one-liner is the same as .NET Framework:

DateTime.Today.ToUniversalTime();

Upvotes: 1

Related Questions