With Noda Time, how to create LocalDateTime using LocalDate and LocalTime

I have LocalDate and LocalTime, and I just want to create a LocalDateTime structure from them. I was thinking about the following extension method, which, in my opinion, would be the fastest, but for no clear reason, the localTime.TickOfMillisecond field does not exist in the current version of the API. So it does not work.

public static LocalDateTime At(this LocalDate localDate, LocalTime localTime) { return new LocalDateTime(localDate.Year, localDate.Month, localDate.Day, localTime.Hour, localTime.Minute, localTime.Second, localTime.Millisecond, localTime.TickOfMillisecond); } 

So, I am stuck at this time to use:

  public static LocalDateTime At(this LocalDate localDate, LocalTime localTime) { return localDate.AtMidnight().PlusTicks(localTime.TickOfDay); } 

Any advice is appreciated.

+6
source share
3 answers

This is much simpler than what you currently have - just use the + operator:

 LocalDate date = ...; LocalTime time = ...; LocalDateTime dateTime = date + time; 
+11
source

There is a method to combine LocalDate and LocalTime to form LocalDateTime

 LocalDate date = ...; LocalTime time = ...; LocalDateTime dateTime=date.atTime(time); 
+2
source

Well, I'm not sure why this is not in the API. Perhaps John Skeet can answer this question.

I see nothing wrong with the way you did in your second example, but you can calculate tickOfMillisecond as follows:

 public static LocalDateTime At(this LocalDate localDate, LocalTime localTime) { var tickOfMillisecond = localTime.TickOfSecond - localTime.Millisecond * 10000; return new LocalDateTime(localDate.Year, localDate.Month, localDate.Day, localTime.Hour, localTime.Minute, localTime.Second, localTime.Millisecond, tickOfMillisecond); } 

Personally, I think LocalDateTime should be a constructor for LocalDateTime , so you can do this instead:

 var ldt = new LocalDateTime(localDate, localTime); 

One more thing - perhaps your extension method should check the date and time as in the same calendar system, and then pass this through the result? I have never used a calendar other than ISO, so I'm not sure about that.

+1
source

All Articles