NSDateFormatter从字符串返回错误的日期 [英] NSDateFormatter return incorrect date from string

查看:243
本文介绍了NSDateFormatter从字符串返回错误的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,

+ (NSDate *) convertToDateFrom:(NSString *) dateString
{
    if (dateString == nil || [dateString isEqual:@""]) return nil; //return nil if dateString is empty
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
        [df setDateFormat:@"EEEE, dd MMMM yyyy HH:mm"];

    NSDate *date = [df dateFromString:dateString];

    return date;
}

当我通过时,

@"Monday, 21 November 2011 17:01" //Passed string

它返回错误的日期,

2011-11-21 23:14:00 +0000 // Output






我不确定我是否在使用正确的那些标志或NSDateFormatter没有正确地将我的字符串转换为日期。


I am not sure whether I am using those flags correctly or NSDateFormatter isn't properly converting my string to date.

我做错了什么?

谢谢

推荐答案

日期末的 +0000 表示格林威治标准时间。所有日期都相对于GMT存储;使用日期格式化程序将日期转换为字符串或反之亦然时,将包含到您的时区的偏移量。您可以使用NSDateFormatter的 -setTimeZone:方法来设置使用的时区。

The +0000 at the end of the date indicates GMT. All dates are stored relative to GMT; when you convert a date to a string or vice versa using a date formatter, the offset to your time zone is included. You can use NSDateFormatter's -setTimeZone: method to set the time zone used.

简而言之,您不是在你的代码中做错了什么。使用 [df stringFromDate:date]; 查看日期是否正确。 (您也可以使用NSDate的 -descriptionWithCalendarFormat:timeZone:locale:。)

In short, you're not doing anything wrong in your code. Use [df stringFromDate:date]; to see that the date is correct. (You can also use NSDate's -descriptionWithCalendarFormat:timeZone:locale:.)

这篇关于NSDateFormatter从字符串返回错误的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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