Recalculate WPF DatePicker value to specific Noda Time DateTimeZone

451 views Asked by At

I'm using Noda Time library in my project to work with Dates. But I need to allow user to enter date/time using DatePicker in specific Noda timezone (non utc, non local/system). How can I achieve that?

Currently I binded my DatePicker to DateTime property and converting this value in property setter to unspecified kind

public DateTime SessionDate
{
   get 
   { 
      return _sessionDate; 
   }
   set 
   { 
       _sessionDate = new DateTime(value.Ticks, DateTimeKind.Unspecified); 
       OnPropertyChanged("SessionDate"); 
   }
}

So, now I have value entered by user represented as DateTime structure with unspecified kind.

But I need to get the UTC value (Noda Instant) from my unspecified SessionDate by applying known DateTimeZone. I tried to use

var instant = new Instant(SessionDateTime.Ticks);
var offset = myTimeZone.GetUtcOffset(instant);
instant = instant.PlusTicks(- offset.Ticks);

but I'm not sure if this is a good approach

1

There are 1 answers

4
Matt Johnson-Pint On BEST ANSWER

If your user is entering time with respect to a specific time zone, then you're not starting with an Instant. You're starting with a LocalDateTime and a DateTimeZone. You need to bind those together to get a ZonedDateTime before you can get to an Instant.

LocalDateTime ldt = LocalDateTime.FromDateTime(SessionDateTime);
ZonedDateTime zdt = ldt.InZoneLeniently(myTimeZone);
Instant instant = zdt.ToInstant();