且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

怎么把MySQL datetime转换成NSDate?

更新时间:2023-02-19 13:59:44

您的格式字符串很接近,但是您也想用SSS指定毫秒:

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"];

此外,您日期字符串中的Z代表"Zulu"(即GMT/UTC),因此您的dateFormat应该使用不带引号的ZX,以便正确解析字符串的时区.另外,如果要从日期构建字符串,请确保相应地设置时区.您还希望设置语言环境:

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];

有关更多信息,请参见技术问题与解答QA1480

See Technical Q&A QA1480 for more information.

您还可以使用更新的NSISO8601DateFormatter,使您摆脱某些杂草:

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;