Search code examples
c#datetimetype-conversionnodatime

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);

Solution

  • 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();