Hours a month, with summer savings

Is there a built-in function to calculate the number of hours per month? He must take care of daylight (which adds or reduces an hour).

+4
source share
1 answer

If you are not in a time zone where midnight is not always valid, you can do something like this (sorry if the VB syntax is a bit off):

Dim start = New DateTime(year, month, day, 0, 0, 0, DateTimeKind.Local) Dim end = start.AddMonths(1) Dim length = end.ToUniversalTime() - start.ToUniversalTime() Dim hours = length.TotalHours 

This is a potential problem if you are somewhere in Brazil, where daylight saving time occurs at midnight local time. Note that the above assumes that you want to use the system-local time zone.

With Noda Time, you can create the corresponding LocalDate values ​​and then convert to ZonedDateTime at the beginning of the corresponding day and play the difference in this way, without any ambiguity. C # example:

 var zone = ... // Whatever DateTimeZone you want... var start = new LocalDate(year, month, day); var end = start.PlusMonths(1); var startInstant = zone.AtStartOfDay(start).ToInstant(); var endInstant = zone.AtStartOfDay(end).ToInstant(); var duration = endInstant - startInstant; var hours = duration.Ticks / NodaConstants.TicksPerHour; 
+3
source

Source: https://habr.com/ru/post/1439398/


All Articles