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#?
DateTime currentTime = TimeZoneInfo. ConvertTime(DateTime. Now, TimeZoneInfo. FindSystemTimeZoneById("Central Standard Time"));
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);
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.).
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.
Try this:
var timeUtc = DateTime.UtcNow; TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); DateTime easternTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, easternZone);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With