Format date string with .000Z into NSDate

一曲冷凌霜 提交于 2019-12-21 04:55:13

问题


I would like to format a date string into a NSDate object, which doesn't sound like a big thing.

The point is, that the date string contains a dot in the timezone value instead of a plus or something else. A date looks like this:

2017-06-04T16:00:00.000Z

I tried format strings like

yyyy-MM-dd'T'HH:mm:ss.ZZZZ
yyyy-MM-dd'T'HH:mm:ss.ZZZ
yyyy-MM-dd'T'HH:mm:ss.Z

Of course I've also checked it on nsdateformatter.com, which works but in xCode the NSDate is always nil.


回答1:


This work for me

var str = "2017-06-04T16:00:00.000Z"
let formato = DateFormatter()
formato.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
formato.timeZone = NSTimeZone(name: "UTC")! as TimeZone
formato.formatterBehavior = .default
var data = formato.date(from: str)



回答2:


In Objective-C

NSString *strValue = @"2017-06-04T16:00:00.000Z";
NSString *dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ"

// Or this if you like get in local time
NSString *dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

NSDateFormatter *dateFmtr = [[NSDateFormatter alloc] init];
[dateFmtr setDateFormat: dateFormat];

// You get a NSDate object
NSDate *dateValue = [dateFmtr dateFromString: strValue];

// Or NSString object
NSString *dateValue = [dateFmtr stringFromDate: dateValue];

Other variants for different strings formats.

// 2018-02-28T16:38:33.6873197-05:00
// If you have this string format you can use
NSString *strDate1 = @"yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ";

For more information with complex formats you can see Patterns Date Format Patterns and the Apple's official documentation Preset Date and Time Styles and Date Formatters




回答3:


I faced the same problem of always getting nils & as a solution you can eliminate the .ZZZZ part from the date String

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

let dateString = openningTimeString.components(separatedBy: ".")[0]

let myDate = dateFormatter.date(from: dateString)


来源:https://stackoverflow.com/questions/44207286/format-date-string-with-000z-into-nsdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!