【问题标题】:Objective-c how to get a date with no time components at GMT timezone?Objective-c 如何在 GMT 时区获取没有时间分量的日期?
【发布时间】:2013-06-10 03:46:24
【问题描述】:

我有一个代码 sn-p,它需要一个日期并尝试将其转换为没有时间组件的日期。然后我使用这些修剪后的数据来保存/获取核心数据。

-(NSDate*)dateWithNoTimeComponents:(NSDate*)startDate
{

    //
    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSNumber* count = 0;
    int secondsPerDay = 86400;


    //break the date and create fractional components for that date
    NSDateComponents *components = [calendar components:(NSWeekdayCalendarUnit| NSHourCalendarUnit | NSMinuteCalendarUnit|NSSecondCalendarUnit) fromDate:startDate];

    NSInteger hour = [components hour];
    NSInteger minute = [components minute];
    NSInteger second = [components second];

    //update daily count
    //remove fractional componets from the date, effectively creating a key per day
    return  [NSDate dateWithTimeInterval:-((hour*60+minute)*60+second) sinceDate:startDate];
}

我担心这可能不适用于来自不同时区的日期。将来自不同时间戳的日期影响此方法?例如,如果我在 GMT -5 时区,然后进入 GMT -8 时区,这种方法产生的修剪日期是否仍然正确? 我是否需要在此计算中的某处包含时区偏移/夏令时以使其全局正确?

【问题讨论】:

    标签: iphone ios objective-c timezone nsdate


    【解决方案1】:

    最好的做法是遵循 SDK 约定,在 GMT 中执行所有操作,只转换为本地时区供用户查看。

    您的代码以小时和分钟为单位进行数学运算,这为极端情况下的错误留下了机会。最好让sdk做数学。要获取给定日期的零小时,请尝试以下操作...

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:(NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:startDate];
    NSDate *justTheDay = [calendar dateFromComponents:components];
    

    【讨论】:

    • 很好的答案,我完全错过了我只能使用年、月和日作为没有时间的日期
    【解决方案2】:

    我以前也采用与 danh 相同的解决方案,但它太耗时(大约 1642.0ms CPU-Time in Instruments' 'Time Profiler ')。多次使用它会减慢我的整个应用程序的速度。

    最后我找到了this answer,并在我的最终方法中使用了它:

    // this method takes around 100ms CPU-time (measured with instruments)
    - (NSDate*) truncateDate : (NSDate*) date
              toCalendarUnit : (NSCalendarUnit) calendarUnit 
    {
        NSDate *truncatedDate;
        [[NSCalendar currentCalendar] rangeOfUnit : calendarUnit
                                        startDate : &truncatedDate
                                         interval : NULL
                                          forDate : date];
        return truncatedDate;
    }
    

    这种方法只花费了大约 100.0ms CPU-Time。

    对我来说,这是一个更好的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      相关资源
      最近更新 更多