2017-06-02 78 views
-3

为什么DateFormatter返回零? 我认为字符串格式匹配?DateFormatter返回零

let dateString = ("01/05/2017")! 
let dateFormatter = DateFormatter() 
dateFormatter.timeZone = TimeZone.current 
dateFormatter.dateFormat = "dd/MMM/yyyy" 
let dateObj = dateFormatter.date(from: dateString) 

执行上面的代码后,dateObj为零。

+1

这只是意味着该字符串不匹配的日期格式。 - Apple提供[数据格式指南](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1)它链接到[日期格式模式](http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns)文档。 –

+2

'let dateString =(“01/05/2017”)!'看起来非常难看。你想在那里解开什么?常规字符串中没有可选值。 –

+0

将您的字符串从'let dateString =(“01/05/2017”)!'让dateString =“01/05/2017” –

回答

1

对于month你需要使用MM因为当你有格式一个月像JanFebMarMMM使用。所以你的dateFormat应该是dd/MM/yyyy

let dateString = "01/05/2017" 
let dateFormatter = DateFormatter() 
dateFormatter.dateFormat = "dd/MM/yyyy" 
let dateObj = dateFormatter.date(from: dateString) 

注:没有必要设置timeZoneTimeZone.current

0

替换为您DATEFORMAT:

dateFormatter.dateFormat = "dd/MM/yyyy" 
0

日期格式化应该是dateFormatter.dateFormat = “DD/MM/YYYY” 在这个案例。

0

您可以从给定链路

NSDateFormatter

对于给定的例如各种检查的日期格式,你可以使用let formaterStrig = "dd/MM/yyyy"