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?
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.
timeIntervalSince1970 is the number of seconds since January, 1st, 1970, 12:00 am (mid night) timeIntervalSinceNow is the number of seconds since now.
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.
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) } }
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/
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