错误的日期从NSDateComponents返回 [英] Wrong date comes back from NSDateComponents
问题描述
为什么这给了我错误的日期?
Why is this giving me the wrong date ?
NSCalendar *myCalendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents* components = [myCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
[components setYear:2013];
[components setMonth:06];
[components setDay:28];
[components setHour:5];
[components setMinute:00];
NSDate *startDate1 = [myCalendar dateFromComponents:components];
NSLog(@"start date is %@",startDate1);
开始日期是2013-06-28 03:00:00 +0000
start date is 2013-06-28 03:00:00 +0000
编辑
我想要做的是以下内容。我有一个开始和结束。
What I want to do is the following. I have a start and endate.
例如:
开始日期是2013-06-28 05:00
start date is 2013-06-28 05:00
结束日期是:2013-06-29 04:59
end date is : 2013-06-29 04:59
然后我想检查当前日期是否在开始和结束之间日期。我使用以下内容。
Then I want to check if the current date is between start and end date. I am using the following.
NSComparisonResult result1 = [now compare:startDate1];
NSComparisonResult result2 = [now compare:endDate1];
if (result2 == NSOrderedSame && result1 == NSOrderedSame ) {
NSLOG(@"OKE!");
}
推荐答案
可能日期是正确的,但是你误解了日志:
Probably the date is correct, but you misunderstood the log:
记录日期总是在TZ +0000中完成。例如,如果您在中欧,您将拥有(预期?)日期2013-06-28 05:00:00 +0200,但日志将显示标准化日期2013-06-28 03:00:00 +0000。这是相同的日期和时间!它只是以不同的方式表达。
Logging a date is always done in TZ +0000. For example, if you are in central europe, you will have the (expected?) date 2013-06-28 05:00:00 +0200, but the log will display the normilzed date 2013-06-28 03:00:00 +0000. This is the same date and time! It is simply expressed in a different way.
+++
如果您的组件位于TZ +0000你也应该设置日历的时区。
If your components are in TZ +0000, too, you should set the time zone of the calendar.
这篇关于错误的日期从NSDateComponents返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!