Reputation: 131
Is there a way to validate the date time if it does exist?
this might sound weird but if you apply daytime saving to a certain zone for example America/New_york March 12. 2017 2am to 3am is their daylight saving time. literary speaking from March 12. 2017 2am to 2:59am it doesn't exist in their time. i wanna validate a given date time if it exist
i tried using this
given dateTime = March 12. 2017 2:30am
var timeZoneProvider = DateTimeZoneProviders.Tzdb.GetZoneOrNull("America/New_York");
var localDate = LocalDateTime.FromDateTime(dateTime);
var result = timeZoneProvider.AtStrictly(localDate).ToDateTimeUtc();
it throws and error is there a way to validate it before using AtStrictly? that where it throws error and says the date time doesn't not exist this is due to DayLight Saving in that zone
Upvotes: 2
Views: 858
Reputation: 241563
The DateTimeZone.MapLocal
method can give you this information. Here are some extension methods that will make this easy. (Put them in a static class somewhere.)
public static bool IsInvalidTime(this DateTimeZone tz, LocalDateTime ldt)
{
return tz.MapLocal(ldt).Count == 0;
}
public static bool IsAmbiguousTime(this DateTimeZone tz, LocalDateTime ldt)
{
return tz.MapLocal(ldt).Count > 1;
}
Then you can do things like this in the spring:
var timeZone = DateTimeZoneProviders.Tzdb["America/New_York"];
var localDateTime = new LocalDateTime(2017, 3, 12, 2, 30);
if (timeZone.IsInvalidTime(localDateTime)) { ... true ... }
and in the fall:
var timeZone = DateTimeZoneProviders.Tzdb["America/New_York"];
var localDateTime = new LocalDateTime(2017, 11, 5, 1, 30);
if (timeZone.IsAmbiguousTime(localDateTime)) { ... true ... }
Of course, this assumes you just want to pre-validate. If you wanted to actually apply some conversion rules, thats where AtLeniently
or ResolveLocal(... your custom rules ...)
would come in.
Upvotes: 5