首页 文章

以固定时间生成NSDate

提问于
浏览
2

我正在尝试生成一个固定小时和分钟的NSDate . 我需要这个与CoreData中存储的其他日期进行相同的比较 .

到目前为止我写了这段代码:

NSDate date = [NSDate date];    
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;   
NSCalendar* calendar = [NSCalendar  currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:date];
NSDate* newDate = [calendar dateFromComponents:components];

但是在xcode4中有一个断点我可以看到值:

Printing description of date:
2012-01-10 11:20:47 +0000
Printing description of newDate:
2012-01-09 23:00:00 +0000

为什么newDate是关于约会的一天?

/ EDIT /

我也尝试手动设置所有组件,但是日历dateFromComponents总是返回相同的一小时返回日期,似乎忽略了组件 .

components.hour=0;
components.minute=0;
components.second=0;
components.timeZone=[NSTimeZone localTimeZone];

这是设置后的组件描述:

<NSDateComponents: 0x7464de0>
    TimeZone: Europe/Rome (CET) offset 3600
    Calendar Year: 2012
    Month: 1
    Day: 10
    Hour: 0
    Minute: 0
    Second: 0

这正是我想要的,但是这个组件的计算日期仍然是

Printing description of newDate:
2012-01-09 23:00:00 +0000

我想知道为什么即使指定NSDateComponents中的所有组件也无法获得精确的NSDate . 仅仅因为NSCalendar忽略了我的要求,组件的含义是什么?

我究竟做错了什么 ?

3 回答

  • 0

    我猜你是01:00时区 . 实际上,NSDate总是给出GMT中的值 . 因此,如果是1月10日00:00,那么GMT时间是1月9日23:00 .

    甚至,在打印以下行时

    2012-01-10 11:20:47 +0000,
    

    它应该比你当前时间少打印1小时 . 请检查 .

  • 3

    用这个....

    NSDate *date = [NSDate date];    
      NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
      [gregorian setLocale:[NSLocale currentLocale]];
      NSDateComponents *nowComponents = [gregorian components:NSYearCalendarUnit |           NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:date];
       NSDate* newDate = [gregorian dateFromComponents:nowComponents];
       NSLog(@"%@\n%@",date,newDate);
    
  • 1

    您可能遇到时区问题,请尝试为日历设置时区 .

相关问题