【问题标题】:Current Time in Date format shows wrong - ios日期格式的当前时间显示错误 - ios
【发布时间】:2016-04-15 18:57:18
【问题描述】:

我正在做一个祈祷警报应用程序,我想将我的当前时间与获取的时间进行比较,但是当我得到我的当前时间时,它总是有一些时差,如图所示;

       // getting today's date string

        NSDate *today = [NSDate date];
        NSDateFormatter *dateFormatterToday = [[NSDateFormatter alloc] init];
        dateFormatterToday.timeZone = [NSTimeZone localTimeZone];
        [dateFormatterToday setDateFormat:@"yyyy-MM-dd HH:mm a"];
        NSString *currentDateTimeString = [dateFormatterToday stringFromDate:today];

        // converting today's date string to NSDATE

        NSDateFormatter *dateFormatterTodayFinal = [[NSDateFormatter alloc] init];
        [dateFormatterTodayFinal setDateFormat:@"yyyy-MM-dd HH:mm a"];
        dateFormatterTodayFinal.timeZone = [NSTimeZone localTimeZone];
        NSDate *dateTodayFinal = [dateFormatterTodayFinal dateFromString:currentDateTimeString];  

这里是currentDateTimeString,格式为string,显示我当前的时间为:

2016-01-11 17:52 PM(这是正确的)

dateTodayFinalDate 格式显示:

2016-01-11 07:22:00 +0000

我已经测试了不同的时区,但问题仍然存在,请帮助某人。谢谢。

【问题讨论】:

  • 将日期格式化为字符串,然后尝试将字符串转回日期的原因是什么?
  • 目前还不清楚您要达到的目标。 dateFormatterTodaydateFormatterTodayFinal的命名表明它不仅仅是来回转换。

标签: ios nsdate nsdateformatter nstimezone


【解决方案1】:

NSDate 没有关于时区的任何信息,当您将鼠标悬停在 xCode 中的 NSDate 上时,它会显示您的时间是 UTC。

如果您想来回转换时间,则此信息(时区)也必须在您要解析的字符串中,并将时区设置回 UTC:

NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone localTimeZone];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSString *currentDateTimeString = [dateFormatter stringFromDate:today];

// converting today's date string to NSDATE
//    
//    NSDateFormatter *dateFormatterTodayFinal = [[NSDateFormatter alloc] init];
//    [dateFormatterTodayFinal setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
dateFormatterToday.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDate *dateTodayFinal = [dateFormatter dateFromString:currentDateTimeString];

还可以查看docs

【讨论】:

    【解决方案2】:

    第二个示例缺少stringFromDate 调用,因此可能使用了使用它自己的格式的描述方法,而不是dateFormatterToday 格式化程序。还缺少打印调用,所以我们只能猜测。

    添加:

    NSString *dateTodayFinalTimeString = [dateFormatterToday stringFromDate:dateTodayFinal];
    NSLog(@"dateTodayFinalTimeString: %@", dateTodayFinalTimeString);
    

    输出:

    dateTodayFinalTimeString: 2016-01-11 07:57 AM

    【讨论】:

    • 详细说明。日期是NSDate 的内部格式,没有格式化程序会改变它。数据格式化程序用于控制字符串和NSDate 表示之间的转换。 NSDate 对象将日期保留为相对于绝对参考日期(2001 年 1 月 1 日 00:00:00 UTC)的时间间隔。
    猜你喜欢
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    相关资源
    最近更新 更多