如何将“2017-07-11T06:52:15.948Z”转换为喜欢“JUL,7 2017”in swift

时间:2017-07-13 12:53:26

标签: ios swift swift3 nsdateformatter

我正在尝试将字符串转换为日期,并再次将日期转换为字符串。

我在下面试过,但它给了我一个零值错误

let string = "2017-07-11T06:52:15.948Z"

let dateFormatter = DateFormatter()
let tempLocale = dateFormatter.locale // save locale temporarily
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from: string)!
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
dateFormatter.locale = tempLocale // reset the locale
let dateString = dateFormatter.string(from: date)
print("EXACT_DATE : \(dateString)")

然后我尝试只使用没有时间的日期,分隔下面的确切字符串

let string = "2017-07-11T06:52:15.948Z"
let dateonly = (string.components(separatedBy: "T"))[0]
let dateformatter = DateFormatter()
dateformatter.dateFormat = "yyyy-mm-dd"
dateformatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale!
let date = dateformatter.date(from: dateonly!)

print(date ?? "no date ")


dateformatter.dateFormat = "MMM d, yyyy" //Your New Date format as per requirement change it own
let newDate = dateformatter.string(from: date!) //pass Date here
print(newDate)

这很好用。但告诉我错误的一个月

希望你对此有所帮助

1 个答案:

答案 0 :(得分:9)

为了参考目的我从here得到答案,追加毫秒SSS

只需更改日期格式

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

获取完整代码

   let string = "2017-07-11T06:52:15.948Z"
    let dateFormatter = DateFormatter()
    let tempLocale = dateFormatter.locale // save locale temporarily
    dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    let date = dateFormatter.date(from: string)!
    dateFormatter.dateFormat = "MMM d, yyyy" ; //"dd-MM-yyyy HH:mm:ss"
    dateFormatter.locale = tempLocale // reset the locale --> but no need here
    let dateString = dateFormatter.string(from: date)
    print("EXACT_DATE : \(dateString)")

<强>输出

enter image description here