obj-C,为什么这给了我昨天的约会?

时间:2011-08-26 06:26:04

标签: iphone objective-c cocoa-touch nsdate

我一直在努力恢复今天的日期,尽可能接近零秒,分钟和小时。所以我可以在各种交易中重复使用相同的日期。

但是,我现在发现我的函数返回昨天的日期?

+ (NSDate *)makeAbsoluteNSDate:(NSDate*)datSource {

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:
           NSGregorianCalendar];
    [calendar setTimeZone:[NSTimeZone localTimeZone]];

    NSDateComponents *dateComponents = [calendar components:NSYearCalendarUnit | 
            NSMonthCalendarUnit | NSDayCalendarUnit
            fromDate:datSource];
    [dateComponents setHour:0];
    [dateComponents setMinute:0];
    [dateComponents setSecond:0];

    NSDate *today = [calendar dateFromComponents:dateComponents];
    [calendar release];

    return today;
}

3 个答案:

答案 0 :(得分:5)

如果您想要在 时区中获取今天或昨天的午夜,那么您应该在 GMT 中获得指向足够时间的NSDate。在我的情况下-2小时,因为我的时区是+0200,所以在2011-08-26的午夜我会得到2011-08-25 22:00。

您必须确保为NSCalendar [NSTimeZone systemTimeZone]设置正确的时区。

我在我的时区中午夜的例行程序是:

+ (NSDate *)midnightOfDate:(NSDate *)date {
    NSCalendar *cal = [NSCalendar currentCalendar];
    [cal setTimeZone:[NSTimeZone systemTimeZone]];

    NSDateComponents *components = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:date];
    [components setTimeZone:[cal timeZone]];

    [components setHour:0];
    [components setMinute:0];
    [components setSecond:0];

    return [cal dateFromComponents:components];
}

所以,在评论中进行讨论之后,这是一个正午函数:

+ (NSDate *)middayOfDate:(NSDate *)date {
    NSCalendar *cal = [NSCalendar currentCalendar];
    [cal setTimeZone:[NSTimeZone systemTimeZone]];

    NSDateComponents *components = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:date];
    [components setTimeZone:[cal timeZone]];

    [components setHour:12];
    [components setMinute:0];
    [components setSecond:0];

    return [cal dateFromComponents:components];
}

答案 1 :(得分:-2)

使用以下功能获取昨天的日期:

- (NSDate *)getDate:(NSDate *)date days:(NSInteger)days hours:(NSInteger)hours mins:(NSInteger)mins seconds:(NSInteger)seconds 
{
     NSCalendar *cal = [NSCalendar currentCalendar];
     NSDateComponents *components = [cal components:( NSHourCalendarUnit |   NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:[[NSDate alloc] init]];

     days = (days*24) + hours; 
     [components setHour:days];
     [components setMinute:mins];
     [components setSecond:seconds];

     NSDate *returnDate = [cal dateByAddingComponents:components toDate:date options:0];
     return returnDate;
 }

在方法调用中获取昨天日期传递日期= [NSDate date],day = -1,hours = 0和mins = 0作为参数。

答案 2 :(得分:-3)

当前日期所需要的只是[NSDate date];时间。