Equivalent of joda LocalTime getMillisOfDay() in n

2019-09-16 06:47发布

问题:

I am porting some code from Java to .NET and looking for a noda-time equivalent of the getMillisOfDay() joda-time method of the LocalTime object.

Is there an equivalent one or must I code my own?

回答1:

In Noda Time 1.x, use the LocalTime.TickOfDay property, and then just divide it by NodaConstants.TicksPerMillisecond to get milliseconds:

LocalTime localTime = ...;
long millis = localTime.TickOfDay / NodaConstants.TicksPerMillisecond;


回答2:

Closest you can get to the number of milliseconds since midnight with out-of-the-box .Net functionality:

dateTime.TimeOfDay.TotalMilliseconds

e.g.

double millisOfDay = DateTime.Now.TimeOfDay.TotalMilliseconds;

TimeOfDay returns the TimeSpan since midnight (time of day) and TotalMilliseconds returns (the name might have given it away) the total number of milliseconds of that TimeSpan.

It's a double by the way, so you'll also get fractions of milliseconds. If you need this a lot, an extension method may be helpful:

public static class DateTimeExtension
{
    // should of course be in pascal case ;)
    public static int getMillisOfDay(this DateTime dateTime)
    {
        return (int) dateTime.TimeOfDay.TotalMilliseconds;
    }
}

int millisOfDay = DateTime.Now.getMillisOfDay();