更改小时后奇怪的NSDate

时间:2018-07-09 07:53:43

标签: ios objective-c timezone nsdate

我想更改NSDate中的小时。我做了这样的事情:

NSDate *final = [gregorian dateBySettingUnit:NSCalendarUnitHour value:hour.intValue ofDate:self.dateForNewEvent options:NSCalendarMatchStrictly];

其中self.dateForNewEvent = 2018-07-09 07:24:13 +0000 和hour.intValue = 5并且我希望日期= 2018-07-09 05:00:00 + 0000但我得到了2018-07-10 03:00:00 UTC。我应该怎么做才能得到预期的日期?

2 个答案:

答案 0 :(得分:0)

我认为您正在将NSDateNSCalendar混合使用:NSDate是一个时间点,内部以UTC表示。要获取在日历或手表上显示的本地日期/时间,请使用NSCalendar

因此,如果您处于MEST(UTC + 2),并且在日历上将时间设置为“ 5”小时,则将是UTC“ 3”小时。

要获取日历的日期/时间,可以使用components(_:from:)中的NSCalendar


只需检查以下代码:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
NSDate * dateForNewEvent = [dateFormatter dateFromString: @"2018-07-09T07:24:13+00:00"];
NSLog(@"dateForNewEvent: %@", dateForNewEvent);


NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear|NSCalendarUnitHour|NSCalendarUnitMinute fromDate:dateForNewEvent];
[comps setHour:5];

NSDate *final = [gregorian dateFromComponents:comps];
NSLog(@"final: %@", final);

预期输出:

  

2018-07-09 11:11:43.542 jdoodle [22:22] dateForNewEvent:2018-07-09 07:24:13 +0000

     

2018-07-09 11:11:43.542 jdoodle [22:22]决赛:2018-07-09 05:24:00 +0000

答案 1 :(得分:0)

要更改特定NSDate的小时数,您需要通过NSDateComponents对其进行操作。请尝试以下代码以实现相同效果:

NSDate *now = [NSDate date]; // YOUR DATE INSTANCE
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond fromDate:now];
[components setHour:5];
NSDate *today5am = [calendar dateFromComponents:components];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
NSLog(@"Date ===>>> %@",[dateFormatter stringFromDate:[NSDate date]]);

希望这会有所帮助!