简体   繁体   中英

how to convert DateTime into Unix TimeStamp in F#?

is there a function / library / easy snippet doing that ?

I've found answers for Python for example, but not F# thanks

I've found the other way round here http://tryfs.net/snippets/snippet-r6

open System

let toDateTime (timestamp:int) = 
    let start = DateTime(1970,1,1,0,0,0,DateTimeKind.Utc) 
    start.AddSeconds(float timestamp).ToLocalTime()

You should be careful because timestamp might be something else than int . However in .NET 4.6.x you should be able to use the functions referred to in the comments.

.NET 4.6.2

Here's an example:

open System
let unix = DateTimeOffset(DateTime.Now).ToUnixTimeSeconds() //val unix : int64 = 1488254491L
let dt =  DateTimeOffset.FromUnixTimeSeconds(unix)  //val dt : DateTimeOffset = 2017/02/28 4:01:31 +00:00
dt.LocalDateTime //val it : DateTime = 2017/02/28 13:01:31

As ToUnixTimeSeconds and FromUnixTimeSeconds operates on DateTimeOffset , either work with that or convert back/forth to DateTime if necessary.

By the way I find it that in the .fsx file the intellisense is a bit flaky for these methods (but works). In .fs files it's OK.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM