How to convert MySQL datetime to NSDate?

杀马特。学长 韩版系。学妹 提交于 2019-12-09 03:22:00

问题


MySQL returns this datetime: 2014-05-07T16:58:44.000Z

How, with what datetime format I can create NSDate?

I far as I found this, but it does not work:

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
NSDate *date = [df dateFromString: valueStr];

回答1:


Your format string is close, but you want to specify the milliseconds with SSS, too:

[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSX"];

Also, the Z in your date string stands for "Zulu" (i.e. GMT/UTC), so your dateFormat should use Z or X without quotes so that it correctly parses the string's time zone. Also, if you're building strings from dates, make sure to set your time zone accordingly. You also want to set your locale, too:

NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.locale = enUSPOSIXLocale;
formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSX";
formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

See Technical Q&A QA1480 for more information.


You can also use the newer NSISO8601DateFormatter, which gets you out of some of those weeds:

NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
formatter.formatOptions = NSISO8601DateFormatWithFullDate | NSISO8601DateFormatWithFullTime | NSISO8601DateFormatWithFractionalSeconds;


来源:https://stackoverflow.com/questions/23527315/how-to-convert-mysql-datetime-to-nsdate

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