0

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?

rene
  • 41,474
  • 78
  • 114
  • 152
Jon
  • 5,247
  • 6
  • 30
  • 38

2 Answers2

4

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;
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks - works fine; although for the original question I think it's TicksPerMillisecond. – Jon Jun 02 '16 at 14:51
0

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();
Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
  • Note this only works if you're either using UTC, or _ignoring the time zone_ (either with `DateTimeKind.Unspecified`, or just treating it as "local" and pretending the time zone doesn't exist), since otherwise this will (potentially) return the wrong value twice a year: `DateTime`, contrary to expectations, is DST/time zone ignorant for all methods and results (except for `ToUniveralTime()`/`ToLocalTime()`. The `TimeSpan` will be an hour short/long on DST days (assuming you're on an hour-different DST zone, and not something else). – Clockwork-Muse Jun 02 '16 at 12:08