Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to convert between noda time LocalDate and Datetime?

I am using both the native Datetime and the Noda Time library LocalDate in the project. The LocalDate is mainly used for calculation whereas Datetime is used in rest of the places.

Can someone please give me an easy way to convert between the native and nodatime date fields?

I am currently using the below approach to convert the Datetime field to Noda LocalDate.

LocalDate endDate = new LocalDate(startDate.Year, startDate.Month, startDate.Day);
like image 334
Theepan subramani Avatar asked Aug 09 '16 06:08

Theepan subramani


2 Answers

The simplest approach would be to convert the DateTime to a LocalDateTime and take the Date part:

var date = LocalDateTime.FromDateTime(dateTime).Date;

I'd expect that to be more efficient than obtaining the year, month and day from DateTime. (Whether or not that's significant for you is a different matter.)

In Noda Time 2.0, there's an extension method on DateTime so you can use:

using static NodaTime.Extensions.DateTimeExtensions;
...
var date = dateTime.ToLocalDateTime().Date;

For the opposite direction, I'd again go via LocalDateTime:

var dateTime = date.AtMidnight().ToDateTimeUnspecified();
like image 139
Jon Skeet Avatar answered Sep 29 '22 00:09

Jon Skeet


The developers of NodaTime API haven't exposed a conversion from DateTime to LocalDate. However, you can create an extension method yourself and use it everywhere as a shorthand:

public static class MyExtensions
{
    public static LocalDate ToLocalDate(this DateTime dateTime)
    {
        return new LocalDate(dateTime.Year, dateTime.Month, dateTime.Day);
    }
}

Usage:

LocalDate localDate = startDate.ToLocalDate();
like image 23
Zein Makki Avatar answered Sep 28 '22 22:09

Zein Makki