ios 以毫秒为单位的 Swift 完整日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37126257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift full date with milliseconds
提问by pableiros
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?
我怎样才能在完整日期中获得毫秒数?
回答by Will
Updated for Swift 3
为 Swift 3 更新
let d = Date()
let df = DateFormatter()
df.dateFormat = "y-MM-dd H:m: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
当您有 时Date
d
,您可以使用 NSDateFormatter 获取格式化的字符串。您还可以使用格式化程序将基于您的格式的字符串日期转换为Date
See this chart for more on what dateFormat can do http://waracle.net/iphone-nsdateformatter-date-formatting-table/
有关 dateFormat 可以做什么的更多信息,请参阅此图表http://waracle.net/iphone-nsdateformatter-date-formatting-table/
回答by slashlos
Swift 5to/from Timestamp String Extension
Swift 5往返时间戳字符串扩展
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)
}
}