【问题标题】:NSLog showing the previous Date显示上一个日期的 NSLog
【发布时间】:2013-04-11 09:34:52
【问题描述】:

我想从两个日期之间添加的核心数据中检索所有条目。我正在使用NSPredicate。由于我没有得到正确的结果,我尝试记录日期。它显示了以前的日期。谷歌搜索了一段时间后,我添加了

[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; 我的代码。现在,它显示正确的日期,但结果仍然错误。

这是我使用的代码。

NSDate *fromDate = [[self dateFormatter]dateFromString:self.fromDateField.text];
NSLog(@"%@",fromDate);
NSDate *toDate = [[self dateFormatter]dateFromString:self.toDateField.text];
NSLog(@"%@",toDate);
NSComparisonResult result = [fromDate compare:toDate];
switch (result) {
    case NSOrderedAscending:
    {
        //code
    }

- (NSDateFormatter *)dateFormatter
{
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil) 
{
    dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
}
   return dateFormatter;
}

提前致谢

【问题讨论】:

    标签: ios objective-c core-data nsdate


    【解决方案1】:

    如果您直接记录 NSDate 对象,它将始终以 GMT/UTC 时区显示该书。您必须记录日期格式化程序的输出。

    NSLog(@"%@",[self.dateFormatter stringFromDate:toDate]);
    

    这将考虑您的时区。或者更好:dateformatter 的日历的时区——如果你不改变它,设备默认是什么。

    【讨论】:

    • 是的,他们现在显示正确的日期。那为什么我得到错误的结果?
    • 您没有得到错误的结果:内部日期始终保存在 UTC 时区。就这些。但是日历知道,即您所在时区的一天在UTC时间的几点开始,就像这样。实际上,日期只是时间的一瞬间,保存为秒。只有在日历中它才有意义,因为日历定义了日、月、年、小时分钟。
    • 所以不要设置时区。把它留给设备。
    • 我删除了时区,但我仍然得到错误的结果。我希望在我给出的两个日期之间添加所有数据,从 14 日到 18 日。我正在获取所有数据但是 18 号添加的那个。请帮忙。
    • 可能你的结果是正确的,你只是在解释它是错误的。或者你在创建过程中搞砸了日期。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    相关资源
    最近更新 更多