Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert DateTime to Eastern Time

I'm trying to create an application that triggers some code when the financial markets are open. Basically in pseudo code:

if(9:30AM ET < Time.Now < 4:00PM ET) {//do something} 

Is there a way I can do this using the DateTime object in C#?

like image 661
locoboy Avatar asked May 13 '11 20:05

locoboy


People also ask

How do I convert DateTime to specific timezone?

DateTime currentTime = TimeZoneInfo. ConvertTime(DateTime. Now, TimeZoneInfo. FindSystemTimeZoneById("Central Standard Time"));

How do I get Eastern time in C#?

For example, if we are going to use Eastern Standard Time, then we can use the code given below. DateTime dateTime_Eastern = TimeZoneInfo. ConvertTimeFromUtc(DateTime. UtcNow, Eastern_Standard_Time);

How do you convert UTC time to local time?

Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.).

How do you change from one time zone to another?

Changing Timezones of ZonedDateTime To convert a ZonedDateTime instance from one timezone to another, follow the two steps: Create ZonedDateTime in 1st timezone. You may already have it in your application. Convert the first ZonedDateTime in second timezone using withZoneSameInstant() method.


2 Answers

Try this:

var timeUtc = DateTime.UtcNow; TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); DateTime easternTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, easternZone); 
like image 120
Dietpixel Avatar answered Sep 20 '22 16:09

Dietpixel


You could probably use the ConvertTime method of the TimeZoneInfo class to convert a given DateTime to the Eastern timezone and do the comparison from there.

var timeToConvert = //whereever you're getting the time from var est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); var targetTime = TimeZoneInfo.ConvertTime(timeToConvert, est); 
like image 23
Roman Avatar answered Sep 19 '22 16:09

Roman