سؤال

I have a LocalDate and a LocalTime and would like to simply create a LocalDateTime struct from them. I thought of the following extension method which I believe would be the fastest but for an obscure reason the field localTime.TickOfMillisecond 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, am I stuck in the mean time to use:

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

Any advice is appreciated.

هل كانت مفيدة؟

المحلول

It's much easier than the way you've got it at the moment - simply use the + operator:

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

نصائح أخرى

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

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

Well, I'm not sure why it's not in the API. Maybe Jon Skeet can answer that.

I don't see anything wrong with the way you went about it in your second example, but you could calculate the tickOfMillisecond like this:

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 there should be a constructor for LocalDateTime so you can do this instead:

var ldt = new LocalDateTime(localDate, localTime);

One other thing - perhaps your extension method should validate the date and time are both in the same calendar system, and then pass that through to the result? I've never used any calendar but ISO, so I'm not sure on that.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top