Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift full date with milliseconds

Tags:

ios

swift

Is any way to print full date with milliseconds?

For example, I'm doing this:

print("\(NSDate())") 

But I'm just get this:

2016-05-09 22:07:19 +0000 

How can I get the milliseconds too in the full date?

like image 808
pableiros Avatar asked May 09 '16 22:05

pableiros


People also ask

How to get date in milliseconds in Swift?

To convert seconds to milliseconds, you need to multiply the number of seconds by 1000. To convert a Date to milliseconds, you could just call timeIntervalSince1970 and multiply it by 1000 every time.

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.

How do you convert date to Millisec?

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(); Still, be careful because in Java the milliseconds obtained are the milliseconds between the desired epoch and 1970-01-01 00:00:00.


2 Answers

Swift 5 to/from Timestamp String Extension

extension String {     static func timestamp() -> String {         let dateFMT = DateFormatter()         dateFMT.locale = Locale(identifier: "en_US_POSIX")         dateFMT.dateFormat = "yyyyMMdd'T'HHmmss.SSSS"         let now = Date()          return String(format: "%@", dateFMT.string(from: now))     }      func tad2Date() -> Date? {         let dateFMT = DateFormatter()         dateFMT.locale = Locale(identifier: "en_US_POSIX")         dateFMT.dateFormat = "yyyyMMdd'T'HHmmss.SSSS"          return dateFMT.date(from: self)     } } 
like image 20
slashlos Avatar answered Sep 28 '22 16:09

slashlos


Updated for Swift 3

let d = Date() let df = DateFormatter() df.dateFormat = "y-MM-dd H:mm:ss.SSSS"  df.string(from: d) // -> "2016-11-17 17:51:15.1720" 

When you have a Date d, you can get the formatted string using a NSDateFormatter. You can also use a formatter to turn a string date based on your format into a Date

See this chart for more on what dateFormat can do http://waracle.net/iphone-nsdateformatter-date-formatting-table/

like image 139
Will Avatar answered Sep 28 '22 16:09

Will