简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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