Apply TimeZone to a specific date? - c#

For example, server time is 11 pm.
User timezone, specified within the app, is US Mountain Standard Time.
So I need to get 4 pm, user time.
Tried with
var UserTimeZoneInfo = "US Mountain Standard Time";
var userTime =TimeZoneInfo.ConvertTimeToUtc(now, _UserTimeZoneInfo);
and this
var userTime = new DateTimeOffset(now, this._UserTimeZoneInfo.BaseUtcOffset);
but in both cases, I get 8am instead of 4pm. TimeZone difference gets added to server time , instead of subtracted. I see there are other DateTime functions, but not sure which one to use ?

You need to use ConvertTimeFromUtc method if you want change to specified timezone time from UTC.
var timeZone = TimeZoneInfo.FindSystemTimeZoneById("US Mountain Standard Time");
DateTime arizonaTime = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(2017, 11, 9, 23, 0, 0,DateTimeKind.Utc), timeZone);
DotNetFiddle

You can use ConvertTime which Converts a time to the time in a particular time zone.
DateTime currentDt = DateTime.Now;
var timeZone = TimeZoneInfo.FindSystemTimeZoneById("US Mountain Standard Time");
var userTime = TimeZoneInfo.ConvertTime(currentDt, timeZone);

Related

Convert date from UTC to local timezone during daylight saving [duplicate]

I'm trying to use DateTimeOffset to convey a specific moment in time across any time zone. I can't figure out how to use TimeZoneInfo to deal with daylight saving time.
var dt = DateTime.UtcNow;
Console.WriteLine(dt.ToLocalTime());
var tz = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
var utcOffset = new DateTimeOffset(dt, TimeSpan.Zero);
Console.WriteLine(utcOffset.ToOffset(tz.BaseUtcOffset));
This prints out:
6/2/2010 4:37:19 PM
6/2/2010 3:37:19 PM -06:00
I am in the central time zone, and and we are currently in daylight saving time.
I am trying to get the second line to read:
6/2/2010 4:37:19 PM -05:00
BaseUtcOffset apparently doesn't change based on DST.
How can I get the the right time with the proper offset value?
You can also use TimeZoneInfo.ConvertTimeFromUtc, which will allow for daylight saving time:
DateTime utc = DateTime.UtcNow;
TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(utc, zone);
You need to get the UtcOffset from the TimeZoneInfo, then pass that to the ToOffset() method:
var dt = DateTime.UtcNow;
Console.WriteLine(dt.ToLocalTime());
var tz = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
var utcOffset = new DateTimeOffset(dt, TimeSpan.Zero);
Console.WriteLine(utcOffset.ToOffset(tz.GetUtcOffset(utcOffset)));
Or better, if you don't want to hard code the time zone identifier:
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.Id);
DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi);
I'm a beginner both at .NET and stackoverflow, so I could be wrong, but here goes:
Using TimeZoneInfo.ConvertTimeFromUtc will allow for daylight saving time, and convert to the correct time according to the time zone + a possible DST offset. However - the offset itself in the resulting object will show the offset for standard time, and not take daylight saving time into account. So if you want to do a ToString on the object, you will end up with the correct time (in hours and minutes), but the wrong offset during daylight saving time, which may lead to the wrong moment in time later in the code.
If you instead use the GetUtcOffset to get the offset for a specific time, and then do a ToOffset on the DateTimeOffset object, both the hours/minutes and the offset itself will be correctly converted, and you can safely do a ToString.
string ExpectedDateTimePattern = "yyyy'-'MM'-'dd'T'HH':'mm':'ss''zzz";
string timeZoneId = "FLE Standard Time";
string dateTimestr = "2017-10-09T09:00:00+02:00";
DateTimeOffset dto = DateTimeOffset.Parse(dateTimeStr);
TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
TimeSpan offset = zone.GetUtcOffset(dto);
dto = dto.ToOffset(offset);
string localTime = dto.ToString(ExpectedDateTimePattern);
localTime will return "2017-10-09T10:00:00+03:00".
datetimeoffset timezoneinfo getutcoffset
This will Adjust automatically... and Return time as per your timezone.
public static string SetLastModified (
TimeZoneInfo csttzi = TimeZoneInfo.FindSystemTimeZoneById(TimeZone.CurrentTimeZone.StandardName);
DateTime cstTime = TimeZoneInfo.ConvertTime(DateTime.UtcNow, csttzi);
return String.Format("DaylightSavingTime: {0}", cstTime.IsDaylightSavingTime().ToString());
}

C# DateTime Convert from string to DateTime in differents TimeZones

I'm struggling with a problem. i have a string date looks like this, "2015-05-02 01:00:00", extracted from a database.
I know that it's british time, but my local time is belgian time.
I'm trying to store the date in UTC and in (CEST or CET depend of the season), converting it from the British time i've extract.
I tried to set Kind property to British time, but the result seems to be in local or utc time. So, i can do half of the job, but not the rest (e.g. I still need the CEST/CET time).
I tried to use this :
string dateString = (string) line["stringDate"];
DateTime ukTime = DateTime.Parse(dateString, new CultureInfo("en-GB", false));
DateTime belgianTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(ukTime, "Romance Standard Time");
The result is the same for both ukTime and belgianTime: 2015-05-02 01:00:00 with kind = unspecified.
It should be 2015-05-02 02:00:00 for belgianTime
If you just add the source time zone to the conversion method it gives the desired answer, even without specifying the IFormatProvider.
string dateString = (string) line["stringDate"];
DateTime ukTime = DateTime.Parse(dateString);
DateTime belgianTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(ukTime,
"GMT Standard Time",
"Romance Standard Time");
This gives time Kind == Unspecified. However if you use:
var belgianTime = TimeZoneInfo.ConvertTime(ukTime,
TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time"),
TimeZoneInfo.Local);
for the conversion, you get Kind == Local
Use the following line of code.
var time = DateTime.Parse(DateTime.Now.ToString());
var clientZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
var utcTime = TimeZoneInfo.ConvertTimeToUtc(time, clientZone);
You have to use the ConvertTime method. ConvertTime
a quick sample -
string s = "2015-05-02 01:00:00";
var dt = new DateTime(2015, 05, 02, 1, 0, 0);
var t = TimeZoneInfo.ConvertTime(dt, TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"));

How can I create a new instance of DateTime in specific time zone?

Given a specific TimeZoneInfo instance how can I create a new DateTime instance in the specified time zone? For example if I have:
var tz = TimeZoneInfo.FindSystemTimeZoneById("US Eastern Standard Time");
var date = new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Unspecified);
Console.WriteLine(TimeZoneInfo.ConvertTime(date, tz));
I am always getting 12/31/2016 7:00:00 PM regardless of what DateTimeKind I define (Utc, Local or Unspecified).
How can I declare a new DateTime that will be January 1st of 2017 at 0:00:00 in US Eastern Standard Time?
You can use TimeZoneInfo to retrieve your zone
You can find timezones here
var zn = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
to express that you are using a local eastern standard time use DateTimeOffset struct instead of DateTime
DateTimeOffset dateTimeOffset = new DateTimeOffset(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Unspecified), zn.BaseUtcOffset);
Why DateTimeOffset
DateTimeOffset is a representation of instantaneous time (also known as absolute time).
you can use the timezoneID as you are using it to specify what timezone you want to create your datetime object.
TimeZoneInfo tzone= TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard
Time");
DateTime dt = DateTime.Now;
later you just convert the datetime to your required timezone.
var datetime2 = TimeZoneInfo.ConvertTimeFromUtc(dt , tzone);
this is the link where you can find all timezones ID. TimeZoneIDs
Thank you, hope this can help you.

How to set a time zone (or a Kind) of a DateTime value?

I mean to store strict UTC time in a DateTime variable and output it in ISO 8601 format.
To do the last I've used .ToString("yyyy-MM-ddTHH:mm:sszzz"), and it has uncovered that the time zone is UTC+01:00.
I've tried to use .Kind = DateTimeKind.Utc, but it says the Kind property has no setter.
How do I explicitly specify the time is in UTC? How is the Kind property set?
If you want to get advantage of your local machine timezone you can use myDateTime.ToUniversalTime() to get the UTC time from your local time or myDateTime.ToLocalTime() to convert the UTC time to the local machine's time.
// convert UTC time from the database to the machine's time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var localTime = databaseUtcTime.ToLocalTime();
// convert local time to UTC for database save
var databaseUtcTime = localTime.ToUniversalTime();
If you need to convert time from/to other timezones, you may use TimeZoneInfo.ConvertTime() or TimeZoneInfo.ConvertTimeFromUtc().
// convert UTC time from the database to japanese time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var japaneseTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
var japaneseTime = TimeZoneInfo.ConvertTimeFromUtc(databaseUtcTime, japaneseTimeZone);
// convert japanese time to UTC for database save
var databaseUtcTime = TimeZoneInfo.ConvertTimeToUtc(japaneseTime, japaneseTimeZone);
List of available timezones
TimeZoneInfo class on MSDN
While the DateTime.Kind property does not have a setter, the static method DateTime.SpecifyKind creates a DateTime instance with a specified value for Kind.
Altenatively there are several DateTime constructor overloads that take a DateTimeKind parameter
You can try this as well, it is easy to implement
TimeZone time2 = TimeZone.CurrentTimeZone;
DateTime test = time2.ToUniversalTime(DateTime.Now);
var singapore = TimeZoneInfo.FindSystemTimeZoneById("Singapore Standard Time");
var singaporetime = TimeZoneInfo.ConvertTimeFromUtc(test, singapore);
Change the text to which standard time you want to change.
Use TimeZone feature of C# to implement.
I hit the time zone problem in System.DateTime in net framework 4.8. I suppose there's a bug in this version of framework.
I ran this piece of code under net framework 4.8 and net 5.0 (+3 is my local time zone).
var dateTime = new DateTime(2021, 3, 3, 12, 13, 14);
var dateTimeKindUtc = new DateTime(2021, 3, 3, 12, 13, 14, DateTimeKind.Utc);
var dateTimeSpecifyKind = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
var dateTimeToUniversalTime = dateTime.ToUniversalTime();
var timeZoneInfoConvertTimeToUtc = TimeZoneInfo.ConvertTimeToUtc(dateTime);
Console.WriteLine($"{nameof(dateTime)} {dateTime:yyyy-MM-ddTHH:mm:sszzz}");
Console.WriteLine($"{nameof(dateTimeKindUtc)} {dateTimeKindUtc:yyyy-MM-ddTHH:mm:sszzz}");
Console.WriteLine($"{nameof(dateTimeSpecifyKind)} {dateTimeSpecifyKind:yyyy-MM-ddTHH:mm:sszzz}");
Console.WriteLine($"{nameof(dateTimeToUniversalTime)} {dateTimeToUniversalTime:yyyy-MM-ddTHH:mm:sszzz}");
Console.WriteLine($"{nameof(timeZoneInfoConvertTimeToUtc)} {timeZoneInfoConvertTimeToUtc:yyyy-MM-ddTHH:mm:sszzz}");
net framework 4.8 output
dateTime 2021-03-03T12:13:14+03:00
dateTimeKindUtc 2021-03-03T12:13:14+03:00
dateTimeSpecifyKind 2021-03-03T12:13:14+03:00
dateTimeToUniversalTime 2021-03-03T09:13:14+03:00
timeZoneInfoConvertTimeToUtc 2021-03-03T09:13:14+03:00
net 5.0 output
dateTime 2021-03-03T12:13:14+03:00
dateTimeKindUtc 2021-03-03T12:13:14+00:00
dateTimeSpecifyKind 2021-03-03T12:13:14+00:00
dateTimeToUniversalTime 2021-03-03T09:13:14+00:00
timeZoneInfoConvertTimeToUtc 2021-03-03T09:13:14+00:00

How to use TimeZoneInfo to get local time during Daylight Saving Time?

I'm trying to use DateTimeOffset to convey a specific moment in time across any time zone. I can't figure out how to use TimeZoneInfo to deal with daylight saving time.
var dt = DateTime.UtcNow;
Console.WriteLine(dt.ToLocalTime());
var tz = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
var utcOffset = new DateTimeOffset(dt, TimeSpan.Zero);
Console.WriteLine(utcOffset.ToOffset(tz.BaseUtcOffset));
This prints out:
6/2/2010 4:37:19 PM
6/2/2010 3:37:19 PM -06:00
I am in the central time zone, and and we are currently in daylight saving time.
I am trying to get the second line to read:
6/2/2010 4:37:19 PM -05:00
BaseUtcOffset apparently doesn't change based on DST.
How can I get the the right time with the proper offset value?
You can also use TimeZoneInfo.ConvertTimeFromUtc, which will allow for daylight saving time:
DateTime utc = DateTime.UtcNow;
TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(utc, zone);
You need to get the UtcOffset from the TimeZoneInfo, then pass that to the ToOffset() method:
var dt = DateTime.UtcNow;
Console.WriteLine(dt.ToLocalTime());
var tz = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
var utcOffset = new DateTimeOffset(dt, TimeSpan.Zero);
Console.WriteLine(utcOffset.ToOffset(tz.GetUtcOffset(utcOffset)));
Or better, if you don't want to hard code the time zone identifier:
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.Id);
DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi);
I'm a beginner both at .NET and stackoverflow, so I could be wrong, but here goes:
Using TimeZoneInfo.ConvertTimeFromUtc will allow for daylight saving time, and convert to the correct time according to the time zone + a possible DST offset. However - the offset itself in the resulting object will show the offset for standard time, and not take daylight saving time into account. So if you want to do a ToString on the object, you will end up with the correct time (in hours and minutes), but the wrong offset during daylight saving time, which may lead to the wrong moment in time later in the code.
If you instead use the GetUtcOffset to get the offset for a specific time, and then do a ToOffset on the DateTimeOffset object, both the hours/minutes and the offset itself will be correctly converted, and you can safely do a ToString.
string ExpectedDateTimePattern = "yyyy'-'MM'-'dd'T'HH':'mm':'ss''zzz";
string timeZoneId = "FLE Standard Time";
string dateTimestr = "2017-10-09T09:00:00+02:00";
DateTimeOffset dto = DateTimeOffset.Parse(dateTimeStr);
TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
TimeSpan offset = zone.GetUtcOffset(dto);
dto = dto.ToOffset(offset);
string localTime = dto.ToString(ExpectedDateTimePattern);
localTime will return "2017-10-09T10:00:00+03:00".
datetimeoffset timezoneinfo getutcoffset
This will Adjust automatically... and Return time as per your timezone.
public static string SetLastModified (
TimeZoneInfo csttzi = TimeZoneInfo.FindSystemTimeZoneById(TimeZone.CurrentTimeZone.StandardName);
DateTime cstTime = TimeZoneInfo.ConvertTime(DateTime.UtcNow, csttzi);
return String.Format("DaylightSavingTime: {0}", cstTime.IsDaylightSavingTime().ToString());
}

Categories

Resources