【问题标题】:Need assistance regarding converting string to date [duplicate]需要有关将字符串转换为日期的帮助 [重复]
【发布时间】:2014-10-30 15:50:41
【问题描述】:
- (void) dateConverter{
    NSString *string = [NSString stringWithFormat:@"%@ %@", [[self dates]objectAtIndex:0], [times objectAtIndex:0]]; // string = 01-10-2014 11:36 AM;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"dd-MM-yyyy hh:mm a"];
    [dateFormatter setLocale:[NSLocale currentLocale]];
    NSDate *date = [[NSDate alloc] init];

    date = [dateFormatter dateFromString:string];
    NSLog(@"dateFromString = %@", date); // 2014-10-01 18:36:00 +0000

    NSTimeInterval timeInterval = [date timeIntervalSince1970];
    NSLog(@"dateFromString = %f", timeInterval); // 1412188560.000000
}

我正在将 string 转换为实际的日期对象,但我得到了不同的行为

字符串 = 01-10-2014 上午 11:36

是我试图转换但得到这个的实际值

2014-10-01 18:36:00 +0000

这有什么问题?

【问题讨论】:

  • 在我看来完全正常。
  • 您在之前的帖子中看到我的回答了吗? stackoverflow.com/questions/26646455/…
  • Swizzling 是最后的解决方案,在这种情况下,所需要的只是使用日期格式化程序。

标签: ios objective-c nsdate nsdateformatter


【解决方案1】:

问题是显示问题。

您正在使用默认的日期格式化程序来打印日期(NSLog 使用了描述方法)。

时间以 UTC (GMT) 显示,看起来您在时区 -0700。时间显示在时区偏移量 0000 中。

系统中的日期/时间基于 GMT 时间,这样可以跨时区比较时间,并且地球上任何地方的时间在同一时间系统中都是相同的。

使用日期格式化程序以您想要的格式获取日期/时间。

示例代码:

NSString *dateString = @"01-10-2014 11:36 AM";
NSLog(@"dateString = %@", dateString);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"dd-MM-yyyy hh:mm a"];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSDate *date = [[NSDate alloc] init];

date = [dateFormatter dateFromString:dateString];
NSLog(@"dateFromString = %@", date);

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

输出:

dateString = 01-10-2014 上午 11:36
dateFromString = 2014-10-01 15:36:00 +0000
显示日期 = 01-10-2014 上午 11:36

注意:您可以提供自己的日期格式以获得您想要的格式。

【讨论】:

  • 我做了这个 NSLog(@"date: %@", [date description]);但结果是一样的:(。我也在控制台中“po date”,但结果是一样的。
  • 是的,因为NSLog 使用description 方法。 Apple 以 GMT (UTC) 以他们想要的方式显示日期。您不在 GMT 时区。使用您自己的日期格式化程序,请参阅答案的补充。
  • 先生,您真了不起。非常感谢。
  • @S.J 好像你第二次就知道了,stackoverflow.com/questions/26646455/…
  • @zaph 先生,如果我尝试在时间间隔内转换“日期”,我遇到了同样的时区问题,我该如何解决?
猜你喜欢
  • 1970-01-01
  • 2021-01-24
  • 2011-08-23
  • 2014-03-14
  • 2011-03-06
  • 1970-01-01
  • 1970-01-01
  • 2021-07-01
  • 1970-01-01
相关资源
最近更新 更多