【问题标题】:How to get the correct date by using dateformatter method?如何使用 dateformatter 方法获取正确的日期?
【发布时间】:2012-05-24 12:27:54
【问题描述】:

这是我的代码:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];

NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:1275822000000+0000];

//字符串是json解析字符串

NSString *formattedDateString = [dateFormatter stringFromDate:date];
NSLog(@"formattedDateString: %@", formattedDateString);

输出是Dec 20,5828963

但我要求的输出是 2010 年 6 月 6 日

如何更改我的代码以获得正确的输出?

【问题讨论】:

  • 只是一点提示;您应该以添加到示例中的更一般的方式来解释您要实现的目标:) 更易于理解
  • 你一定有问题 12758220000000000。你从哪里得到这个值?
  • 日期格式化程序工作正常,12758220000000000 是错误的数字 - 它是什么意思以及它来自哪里?
  • @StianStorrvik 嗨,朋友,我将字符串传递给 NSdate 对象,我认为它转换了日期,但输出错误。在 Jave 中,此字符串执行 2010 年 6 月 6 日。但输出为 12 月 20,5828963跨度>
  • 你从哪里得到这个号码的?因为它看起来很高,Dec 20,5828963 似乎是正确的。

标签: ios xcode4.2 nsdateformatter


【解决方案1】:

如果您想从某个幻数收到 2010 年 6 月 6 日,请使用:

NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:297475822];

由于某种原因,您的数字非常大,正如@wrock 所说,它会乘以 1000 万,因此为了获得正确的值,您可以使用 dateWithTimeIntervalSince1970 并将其除以 1000 万

NSDate *date = [NSDate dateWithTimeIntervalSince1970:1275822000];

【讨论】:

  • 没错。 dateWithTimeIntervalSinceReferenceDate: 接受自 2001 年 1 月 1 日 GMT 以来的秒数。 12758220000000000 秒是很长的时间。
  • 哦,朋友,这是一个服务字符串。我该如何更改
  • 这似乎是一个 Unix 时间戳乘以一千万。使用[NSDate dateWithTimeIntervalSinceReferenceDate:(whatYourServiceGaveYou*1.0e-7-NSTimeIntervalSince1970)]
  • 是的,1275822000 是使用dateWithTimeIntervalSince1970 方法的真实数字
  • @beryllium 感谢您的指出,我完全忘记了那条消息。
【解决方案2】:

首先:您的时间戳看起来像一个 Java 时间戳,但它有几个额外的零(其中 4 个正好)。您必须将其转换为 Unix 时间戳,即自 Unix 纪元以来的秒数(与 Java 相反,它是自 Unix 纪元以来的毫秒数)。

dateWithTimeIntervalSinceReferenceDate: 不接受 Unix 时间戳,但转换很简单:

double timestampFromService = 12758220000000000;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:
    (timestampFromService*1.0e-7)];

【讨论】:

    【解决方案3】:

    以可读的方式使用日期:

    NSDate *myDate = [NSDate dateWithString:@"2010-06-06 00:00:00"];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
    
    NSString *formattedDateString = [dateFormatter stringFromDate:myDate];
    NSLog(@"formattedDateString: %@", formattedDateString);
    

    【讨论】:

    • 但我的字符串是@"12758220000000000"
    • 所以你的字符串不正确。这不是 2010 年 6 月 6 日。您的代码很好。
    猜你喜欢
    • 1970-01-01
    • 2020-11-05
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 2023-04-10
    • 2020-11-16
    • 2019-06-25
    相关资源
    最近更新 更多