获取NSDate今天与00:00:00作为时间 [英] Getting NSDate for today with 00:00:00 as time

查看:302
本文介绍了获取NSDate今天与00:00:00作为时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Xcode中写了一个分类,它将扩展当前的NSDate类。

I am writing a categorie in Xcode, that would extend the current NSDate class. I want to add two methods which I use regularly and somehow I can't get them to work properly.

目前我有这个代码:

+ (NSDate*) today
{
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *todayComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:[NSDate date]];
    NSInteger theDay = [todayComponents day];
    NSInteger theMonth = [todayComponents month];
    NSInteger theYear = [todayComponents year];

    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setDay:theDay]; 
    [components setMonth:theMonth]; 
    [components setYear:theYear];

    NSDate* todayDate = [gregorian dateFromComponents:components];

    [components release];
    [gregorian release];

    return todayDate;
}



我希望它返回如下日期:2010-11-03 00:00:00 +01。但是不知何故,时区保持臭名昭着,因为这段代码返回2010-11-02 23:00:00 +0000。

I want it to return a date like this: "2010-11-03 00:00:00 +01". But somehow the timezone keeps buggin me, because this code returns "2010-11-02 23:00:00 +0000".

任何人都可以告诉我如何解决这个问题代码实际返回正确的日期?或者我可以使用这个日期,我的应用程序将自己转换它本身,因为时区的机器设置为

Can anyone tell me how to fix this code to actually return the correct date? Or can I just use this date and my application will convert it itself because of the timezone the machine is set to.

我必须在我的应用程序中记录某些事件数据库,也只是使用[NSDate date]方法。这是否意味着[NSDate date]方法也使用没有时区信息的时间?

I have to log certain events in my app to a database, which also just uses the [NSDate date] method. Does that mean that the [NSDate date] method also uses the time without timezone information?

编辑:
我认为它与夏令时有关时间bug。我看到的东西是完全一样的可能是时钟应用程序,与错误,使人们醒来晚了。此外,TimeZone默认为您设备上当前设置的TimeZone,因此应保持不变,直到您更改设置屏幕中的时区。

I think it has something to do with the Daylight savings time bug. The things I see is exactly the same as probably the Clock app has, with the bug making people wake up late. Also, the TimeZone defaults to the TimeZone currently set on your device, so it should stay the same until you change the timezone in your settings screen.

EDIT2:
Ok,some more tests:

Ok, some more tests:

NSLog(@"CurrentDate: %@", [NSDate date]);
NSLog(@"TZ: %@", [NSTimeZone defaultTimeZone]);

给我以下结果:

2010-11-03 23:23:49.000 App[8578:207] CurrentDate: 2010-11-03 22:23:49 +0000
2010-11-03 23:23:49.001 App[8578:207] TZ: Europe/Amsterdam (GMT+01:00) offset 3600


推荐答案

请参阅使用时区。您需要使用NSCalendar的 -setTimeZone:方法,然后再开始请求日期。

See Using Time Zones. You'll want to set the calendar's time zone using NSCalendar's -setTimeZone: method before you start asking it for dates.

这篇关于获取NSDate今天与00:00:00作为时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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