How to convert milliseconds to date string in swif

2019-06-22 14:24发布

This question already has an answer here:

I am trying to convert milliseconds to date string in swift 3,i tried by setting date fomatter but i am not getting current date string.

var milliseconds=1477593000000

let date = NSDate(timeIntervalSince1970: TimeInterval(milliseconds))
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
formatter.locale = NSLocale(localeIdentifier: "en_US") as Locale!
print(formatter.string(from: date as Date))

output:

22-01-48793 01:30:00

标签: ios swift3
3条回答
狗以群分
2楼-- · 2019-06-22 14:54

How about trying this -

    let milisecond = 1479714427
    let dateVar = Date.init(timeIntervalSinceNow: TimeInterval(milisecond)/1000)
    var dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy hh:mm"
    print(dateFormatter.string(from: dateVar))
查看更多
The star\"
3楼-- · 2019-06-22 14:56

Have a look at the documentation of NSDate:

convenience init(timeIntervalSince1970 secs: TimeInterval)

Returns an NSDate object initialized relative to the current date and time by a given number of seconds.

Just convert your milliseconds to seconds and you should get the correct date.

查看更多
乱世女痞
4楼-- · 2019-06-22 15:11

Try this,

var date = Date(timeIntervalSince1970: (1477593000000 / 1000.0))
print("date - \(date)")

You will get output as date :

date - 2016-10-27 18:30:00 +0000

查看更多
登录 后发表回答