简体   繁体   English

使用NSDateFormatter从NSString进行日期格式化

[英]date formatting from a NSString using NSDateFormatter

I have the following string representing a date & time 我有以下字符串表示日期和时间

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

(no spaces (apart from a single space in front of the time), just as it is above) (没有空格(除了前面的单个空格),就像它在上面一样)

I would like to format this date using: 我想使用以下格式来格式化此日期:

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];

If you change your string slightly to match the format of your input exactly, it works fine. 如果您稍微更改字符串以完全匹配输入的格式,则可以正常工作。 All you need to do is removing spaces and the comma from the string, like this: 您需要做的就是从字符串中删除空格和逗号,如下所示:

"EEEdMMMyyyy HH:mm"

With this string I get the result below: 使用此字符串,我得到以下结果:

08.Apr.2012 19:00 +0000

It is 19:00 , not 15:00 , because my time zone is four hours behind GMT. 现在是19:00 ,而不是15:00 ,因为我的时区比GMT落后4个小时。

[inputFormatter setDateFormat:@"EEEddMMMyyyy HH:mm"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM