NSDate在月初返回错误的日期 [英] NSDate returns wrong date on the first of month

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

问题描述

我的应用程序使用[NSDate date]功能获取当前日期。除了 AM 之前的每个月的第1天,其他日子的工作都很好。即遵循以下步骤:

My app used [NSDate date ] function to get current date. Its work fine other days except 1st of every month during AM. i.e Follow Following steps :


  1. 将系统日期设置为01 - 2011年6月和时间在00.00午夜到5.59之间。

  2. 使用以下代码:

    NSLog(@当前日期::%@,[NSDate日期]);

  1. Set the system date as 01 - June - 2011 & time between 00.00 midnight to 5.59 AM.
  2. Use following code :
    NSLog(@"Current Date :: %@",[NSDate date]);

O / P是:: :: 2011-05-31 19:40:21 +0000

The O/P is :: Current Date :: 2011-05-31 19:40:21 +0000

希望的O / P是:: 当前日期:: 2011-06 -01 00:00:0(设定的时间)+0000

Desired O/P is :: Current Date :: 2011-06-01 00:00:0( i.e.the time which is set ) +0000

另外从 6 AM 可以正常工作。

这是什么原因?

其实我不希望NSDate的字符串格式,但我想要的是NSDate日期对应于当月的第一个日期。我使用以下代码片段:

Actually I don't want NSDate in string format but what I want is NSDate date object corresponding to 1st date of current month. For which i use following snippet of code :

NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

NSDateComponents *comp = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit 
| NSDayCalendarUnit) fromDate:[NSDatedate]];

[comp setDay:1];     

NSDate *firstDayOfMonthDate = [gregorian dateFromComponents:comp];

[gregorian release];

return firstDayOfMonthDate;

由于[NSDate date]返回错误的日期,组件也包含错误的日期。以上代码适用于所有senario,除了我在该线程的开头发布的senario。我该怎么办?

Since [NSDate date] returns wrong date, components also contains wrong date. The above code works for all senario except the senario which i posted in beginning of this thread. What should I do?

推荐答案

最后得到解决方案:

strong> NSDate对象没有与他们相关的时区,并且有一些发布回苹果的人决定NSDate的描述方法,这是NSLog使用的,应该使用GMT + 0而不是本地时间输出区。 (我假设有人有一个错误,他们损坏了他们的区域设置,并导致NSDate的描述方法崩溃,所以错误报告已经提交...)

The point is, NSDate objects don't have a time zone associated with them, and a few releases back someone in Apple decided that NSDate's -description method, which is what NSLog uses, should use GMT+0 and NOT the local time zone for output. (I assume someone had a bug where they corrupted their locale setting, and that caused NSDate's -description method to crash, and so bug reports got filed...)

简短版本:使用NSDateFormatter输出日期。不要使用-description

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

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