【问题标题】:NSString to NSDate is giving the wrong day [duplicate]NSString 到 NSDate 给出了错误的日期 [重复]
【发布时间】:2014-01-18 06:07:50
【问题描述】:

我有这段代码:

NSDateFormatter* df = [[NSDateFormatter alloc] init];
df.locale = [NSLocale currentLocale];
df.timeZone = [NSTimeZone localTimeZone];
df.timeStyle = NSDateFormatterShortStyle;
df.dateStyle = NSDateFormatterShortStyle;
df.locale = [NSLocale currentLocale];
[df setDateFormat:@"dd/MM/yyyy"];
NSString *todaysDate = @"31/12/2013";
NSDate* today = [df dateFromString:todaysDate];

NSLog(@"comparing todaysDate: %@ with today: %@",todaysDate,today);

当我检查我的控制台时,我看到 todaysDate 是 31/12/2013 而今天是 2013-12-30 21:00:00 +0000 我不明白为什么它会在过去 1 天...帮帮我?我试图基本上根据日期过滤掉字典中的一些项目。此处不包括过滤部分,因为已确定 dateFromString 没有完成其工作。

【问题讨论】:

  • 检查您的设备设置->常规->日期和时间->设置->常规->国际->区域格式的时区和设备
  • 是的,你的时间设置有问题。在在线 Objective C 编译器中检查代码是完美的
  • "31/12/2013" 在您的时区中与 "2013-12-30 21:00:00 +0000" 相同(以 UTC 报告时间)。 - 这个问题经常被问及回答,见上面的“可能重复”或谷歌“NSDate 错误”。

标签: ios objective-c


【解决方案1】:

这很可能是因为您的 TimeZone。你似乎是 GMT+3 或类似的东西。如果您更改本地时区,应该没问题。

您应该使用:df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]: 而不是 localTimeZone,以便即使在不同的时区也始终获得相同的结果。

【讨论】:

  • 就是这样!谢谢赞福德
  • 不客气!我住在 GMT+1 区域,我经常看到这类问题... ;o) 顺便说一句,新年快乐...
  • 我将在未来将这段代码添加到我所有的应用程序中哈哈...祝大家新年快乐:)
【解决方案2】:

将以下内容添加到您的 NSDateFormatter。

[df setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

【讨论】:

    【解决方案3】:

    当我使用日期编程时,我总是使用此代码,很抱歉,我无法帮助您将 NSString 转换为 NSDate,因为我自己不使用该代码

    雇佣可以解决您的问题:

    #include <ctime>
    #include <iostream>
    using namespace std;
    
    int main() {
    time_t t = time(0);   // get time now
    struct tm * now = localtime( & t );
    cout << (now->tm_year + 1900) << '-' 
         << (now->tm_mon + 1) << '-'
         <<  now->tm_mday
         << endl;
    }
    

    【讨论】:

    • 如果您知道确切的答案或与答案有点相关。然后只在此处发布您的答案。这完全无关紧要。你知道xcode工具吗?
    • 这不是答案。
    猜你喜欢
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    相关资源
    最近更新 更多