NSDateFormatter:如何将带有'GMT'的日期字符串转换为本地NSDate? [英] NSDateFormatter: how to convert date string with 'GMT' to local NSDate?

查看:122
本文介绍了NSDateFormatter:如何将带有'GMT'的日期字符串转换为本地NSDate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将从服务器检索到的日期字符串转换为本地NSDate,字符串如下所示:

I need to convert a date string retrieved from a server, to local NSDate, the string looks like:

"Fri, 30 Nov 2012 00:35:18 GMT"

但现在是11月30日星期五,11 :36 AM,那么如何将字符串转换为有意义的本地NSDate?

But now it is Friday, 30th Nov, 11:36 AM, so how do I convert the string to a meaningful local NSDate?

我发现:

iPhone:NSDate将GMT转换为当地时间

但看起来却恰恰相反。

推荐答案

请注意,NSDate始终存储日期,在GMT内部。然后使用日期格式化程序在本地时区创建字符串。在这种情况下,您开始使用字符串,因此需要使用日期格式化程序首先创建日期,然后再次使用它在本地时区创建一个字符串(默认情况下,时区不是指定)。

Note that NSDate's always store the date, internally, in GMT. You then use a date formatter to create a string in your local time zone. In this case, you are starting with a string so need to use the date formatter to create the date in the first place, and then use it again to create a string in your local time zone (which it defaults to when the timezone is not specified).

NSString *dateString           = @"Fri, 30 Nov 2012 00:35:18 GMT";

NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.dateFormat       = @"EEE, dd MM yyyy HH:mm:ss zzz";

NSDate *date                   = [dateFormatter dateFromString:dateString];
NSString *localDateString      = [dateFormatter stringFromDate:date];

NSLog(@"%@", localDateString);
// Results:  Thu, 29 11 2012 19:35:18 EST

这篇关于NSDateFormatter:如何将带有'GMT'的日期字符串转换为本地NSDate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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