怎么把MySQL datetime转换成NSDate? [英] How to convert MySQL datetime to NSDate?

查看:89
本文介绍了怎么把MySQL datetime转换成NSDate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MySQL返回此日期时间: 2014-05-07T16:58:44.000Z

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

如何使用什么日期时间格式,我可以创建 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];

推荐答案

您的格式字符串很接近,但是您也想用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;

这篇关于怎么把MySQL datetime转换成NSDate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆