How to find to find 'today at midnight' in .NET?

117 Views Asked by At

We have a cron job scheduled at 'every day 3pm paris,' 'every day 3pm new york,' etc

In our code, the logic is to find all transactions realized between midnight and noon in the specified timezone

Currently, we are doing this to find midnight (then adding AddHours(12) to find noon)

var tz = TimeZoneInfo.FindSystemTimeZoneById(tzId); //tzId is a param of the job
var midnightAtTz = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, tz).Date;

It seems to work, however we do not understand why and we do not understand what would be the correct way to do it

Some things that do not work but would make more sense

DateTime.Today => relies on the server TZ
TimeZoneInfo.ConvertTime(DateTime.Today, tz).Date; => throws exception if tz is not the one of the machine, System.ArgumentException: The UTC Offset of the local dateTime parameter does not match the offset argument. (Parameter 'offset')

Questions:

  1. Why is .Date working fine even if this is DateTime and not DateTimeOffset?
  2. Is this the correct way to find midnight in a specific timezone?
0

There are 0 best solutions below