HardyBoi
HardyBoi

Reputation: 21

F# - convert time in microsecond to day of the week

I am trying to learn F# and was wondering if i have a json object which has time in microseconds as int. I want to get the day, date and time out of this and was wondering how to do it.

Upvotes: 0

Views: 116

Answers (1)

libertyernie
libertyernie

Reputation: 2686

I actually happen to have needed to do this recently. You'll almost certainly want to use the .NET time objects (DateTime, DateTimeOffset, TimeSpan) in some capacity. Here's what I went with:

let TicksPerMicrosecond =
    TimeSpan.TicksPerMillisecond / 1000L

let FromUnixTimeMicroseconds (us: int64) =
    DateTimeOffset.FromUnixTimeMilliseconds 0L + TimeSpan.FromTicks(us * TicksPerMicrosecond)

From TimeSpan.TicksPerMillisecond we can calculate how many are in a microsecond (if I remember correctly it's 10, but this way it doesn't seem as "magic"). Then I can convert the microseconds value into ticks and add it to the epoch date.

To get the day of the week (assuming the time zone is UTC), you'd just use DateTimeOffset.DayOfWeek.

Upvotes: 2

Related Questions