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
To convert milliseconds to seconds, divide the number of milliseconds by 1000 and then call the Date(timeIntervalSince1970:) with the resulting seconds. To avoid having to do this every time, you can write an extension to do it.
String myDate = "2014/10/29 18:10:45"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = sdf. parse(myDate); long millis = date. getTime();
timeIntervalSince1970 is the number of seconds since January, 1st, 1970, 12:00 am (mid night) timeIntervalSinceNow is the number of seconds since now.
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
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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With