Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

datetime

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?

like image 461
Marko Avatar asked Jul 24 '17 20:07

Marko


People also ask

How do I make DateTime now aware time zone?

Timezone aware object using datetime now(). time() function of datetime module. Then we will replace the value of the timezone in the tzinfo class of the object using the replace() function. After that convert the date value into ISO 8601 format using the isoformat() method.

Is DateTime stored with timezone?

The point in time is saved as a Unix timestamp, regardless of the time zone or daylight saving time. The time zone affects how the values of the DateTime type values are displayed in text format and how the values specified as strings are parsed ('2020-01-01 05:00:01').

What is timezone for Created date Salesforce?

Rule #2 – DateTime objects are saved in GMT In Salesforce, every time you instantiate and insert a DateTime object, it gets saved in the database in GMT Time Zone and it is translated to the user's time zone when reading it.

Which function changes date from one timezone to another?

setTimeZone() method to convert the date time to the given timezone.


2 Answers

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).

like image 163
BRAHIM Kamel Avatar answered Nov 04 '22 03:11

BRAHIM Kamel


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.

like image 36
Sergio Cabrera Gari Avatar answered Nov 04 '22 03:11

Sergio Cabrera Gari