Equivalent of joda LocalTime getMillisOfDay() in n

2019-09-16 06:25发布

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?

2条回答
ら.Afraid
2楼-- · 2019-09-16 06:35

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();
查看更多
爷、活的狠高调
3楼-- · 2019-09-16 06:45

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;
查看更多
登录 后发表回答