Best way to convert between noda time LocalDate and Datetime?
Asked Answered
H

3

6

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);
Heiser answered 9/8, 2016 at 6:9 Comment(0)
L
9

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();
Launcelot answered 9/8, 2016 at 6:26 Comment(0)
C
25

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();
Choe answered 9/8, 2016 at 21:24 Comment(2)
How can I get the Time component from the LocalDateTime?. I've created a LocalDateTime as var dateTime = new LocalDateTime(2017, 8, 01, 22, 30, 00); If I follow your approach, I'm able to get the Date alone and not the time.Profound
@Karthik: Use the TimeOfDay property to get the LocalTime.Choe
L
9

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();
Launcelot answered 9/8, 2016 at 6:26 Comment(0)
S
0

Today you can use:

LocalDate.FromDateTime(dateTime);
Sermon answered 19/6, 2024 at 10:1 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.