Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert milliseconds to date string in swift 3 [duplicate]

Tags:

ios

swift3

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
like image 957
dark knight Avatar asked Nov 21 '16 07:11

dark knight


People also ask

How do you convert milliseconds to Date and time in Swift?

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.

How to get milliseconds from Date?

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();

What is timeIntervalSince1970?

timeIntervalSince1970 is the number of seconds since January, 1st, 1970, 12:00 am (mid night) timeIntervalSinceNow is the number of seconds since now.


3 Answers

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

like image 178
KAR Avatar answered Oct 23 '22 21:10

KAR


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))
like image 39
Saheb Roy Avatar answered Oct 23 '22 21:10

Saheb Roy


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.

like image 23
FelixSFD Avatar answered Oct 23 '22 19:10

FelixSFD