【问题标题】:date formatting from a NSString using NSDateFormatter使用 NSDateFormatter 从 NSString 格式化日期
【发布时间】:2012-02-05 11:23:15
【问题描述】:

我有以下代表日期和时间的字符串

NSString *shortDateString = @"Sat28Apr2012 15:00";

(没有空格(除了时间前面的一个空格),和上面一样)

我想使用以下格式设置此日期:

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
// Question is regarding the line below:
[inputFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm"];

NSDate *formatterDate = [inputFormatter dateFromString:shortDateString];

NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[outputFormatter setTimeZone:gmt];
[outputFormatter setDateFormat:@"dd.MMM.yyyy HH:mm Z"];

NSString *newDateString = [outputFormatter stringFromDate:formatterDate];

【问题讨论】:

  • 您的字符串缺少有关年份的信息。
  • 那么年份和时间之间是否有空格,或者“没有空格,就像上面一样”评论仍然适用?
  • 谢谢老哥,我也解决了,时间前面只有一个空格字符串和shortDateString中的一样

标签: iphone objective-c ipad nsdate nsdateformatter


【解决方案1】:

如果您稍微更改字符串以完全匹配输入的格式,它可以正常工作。您需要做的就是从字符串中删除空格和逗号,如下所示:

"EEEdMMMyyyy HH:mm"

有了这个字符串,我得到以下结果:

08.Apr.2012 19:00 +0000

19:00,而不是15:00,因为我的时区比格林威治标准时间晚四个小时。

【讨论】:

    【解决方案2】:
    [inputFormatter setDateFormat:@"EEEddMMMyyyy HH:mm"];
    

    【讨论】:

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