How to convert DateTime to Eastern Time

C#asp.netDatetime

C# Problem Overview


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#?

C# Solutions


Solution 1 - C#

Try this:

var timeUtc = DateTime.UtcNow;
TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime easternTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, easternZone);

Solution 2 - C#

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

Solution 3 - C#

You need to split up the logic into two;

  • Check if date is more than start date, startTime > now
  • Check if date is less than end date, endTime < now

For a date range the logic should satisfy both (with logical AND, &&).

DateTime startTime = DateTime.Today.AddHours(9).AddMinutes(30);
DateTime endTime = DateTime.Today.AddHours(12+4);
DateTime now = DateTime.Now;
if(startTime > now && endTime < now) {
    // do something
}

If you're in ET timezone it should work fine, but otherwise you need to do some timezone manipulation. Check the other answers.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlocoboyView Question on Stackoverflow
Solution 1 - C#DietpixelView Answer on Stackoverflow
Solution 2 - C#RomanView Answer on Stackoverflow
Solution 3 - C#SpoikeView Answer on Stackoverflow