Reputation: 6590
I want to get midnight time of specific timezone in UTC. For e.g. consider my local machine timezone is +05:30. Please see below screenshot. I used https://www.epochconverter.com/ site for conversion.
In above example I enter midnight time in +05:30 and it give UTCtime for it.
Note: I am resetting my machine timezone to (UTC)Coordinated Universal Time.
So here what I want to find is, that UTC datetime. For this I have stored user timezone information. I get timezone info using below code.
TimeZoneInfo userTz = TimeZoneInfo.FindSystemTimeZoneById(LoginSessionDO.TimeZoneId);
So, I want to find midnight time of any timezone in UTC. How can I do that in c#?
for e.g. +05:30 - 2018-07-07 00:00:00 UTC- 2018-07-06 18:30:00
Sorry for uncleared question. I will explain my scenario.
EDIT:-
I have stored some user's activity data in Sql server
table which contains dateofactivity
column. All records datetime stored in UTC. So in frontend side, I want to fetch all todays activity records of user from midnight(When days start). If user is in +05:30
timezone & he want to fetch all 7th July 2018 00:00:00 records then I need to pass 6th July 2018 18:30:00.Now suppose another user is in Europe/Amsterdam (CEST) GMT +02:00 so want to find midnight time of Europe/Amsterdam in UTC.
Upvotes: 6
Views: 7737
Reputation: 331
Take the midnight time in your local timezone, get the timezone info for your timezone and call ConvertTimeToUtc
var tz = TimeZoneInfo.FindSystemTimeZoneById("Sri Lanka Standard Time");
var midnight = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Unspecified);
var converted = TimeZoneInfo.ConvertTimeToUtc(midnight, tz);
Console.WriteLine(midnight); //2000-01-01 00:00:00
Console.WriteLine(converted);//1999-12-31 18:30:00
Upvotes: 8
Reputation: 5278
Use DateTimeOffset
.
It takes a DateTime
and a TimeSpan
for the offset, which you can use as the time zone, and has a ToUniversalTime
method.
There is also good documentation that covers this topic: https://learn.microsoft.com/en-us/dotnet/standard/datetime/
Upvotes: 1
Reputation: 144
var midNightTime = new DateTime(2018, 7, 7, 0, 0, 0);
TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); // USE YOUR TIMEZONE INFO HERE INSTEAD.
DateTime dateTimeInZone = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(midNightTime, timeZone.StandardName);
DateTime universalTime = dateTimeInZone.ToUniversalTime();
Also if you are only looking for offset see here - Get Timezone Offset of Server in C#
Upvotes: 2
Reputation: 61
Now datetime in UTC:
DateTime.UtcNow()
Parse to UTC:
DateTime.Parse("2018-05-08 12:00:00").ToUniversalTime()
Parse to Local Time:
DateTime.Parse("2018-05-08 00:00:00").ToLocalTime()
Upvotes: -2