I have a fairly straightforward notion that I want to represent using Noda Time:
04/24/2015 4:00pm America/New_York
To create an unambiguous representation, I've done the following:
var _americaNewYork = DateTimeZoneProviders.Tzdb["America/New_York"];
var pattern = LocalDateTimePattern.CreateWithInvariantCulture("M/d/yyyy h:mmtt");
var localTime = pattern.Parse(formattedDatetime).Value;
var zonedDateTime = localTime.InZoneLeniently(_easternTime);
Is there a more concise way to do what I did above? I feel like I should be able to do this with one or two lines instead:
var unambiguous = new ZonedDateTime(string textToParse, DateTimePattern pattern, string timezone);
And maybe a few overloads if I really want to specify gap semantics when changes occur.
I'd say that what you've got is actually the best approach at the moment - you're parsing to the right type, in that what you've got in your text ("04/24/2015 4:00pm") really is a local time. (If you've actually got the "America/New_York" bit in there, you should definitely just use a ZonedDateTimePattern
.)
But you can use a ZonedDateTimePattern
anyway, with an appropriate resolver and template value:
var tzdb = DateTimeZoneProviders.Tzdb;
var pattern = ZonedDateTimePattern.Create(
"M/d/yyyy h:mmtt",
CultureInfo.InvariantCulture,
Resolvers.LenientResolver,
tzdb,
NodaConstants.UnixEpoch.InZone(tzdb["America/New_York"]));
string text = "04/24/2015 4:00pm";
var zoned = pattern.Parse(text).Value;
Console.WriteLine(zoned);
Obviously that's more code to start with, but you can reuse the pattern multiple times.
As I say, I'd personally stick with what you've got as it says exactly what you're trying to do: parse a LocalDateTime
and then resolve that into a particular zone.
See more on this question at Stackoverflow