I recently encountered a problem of time String Conversion during XML parsing of Sina RSS news.
The problem is: Wed, 3 Apr 2013 04:11:02 GMT (this data is obtained in the XML file) to extract 04:11:02 from this string.
Note: For GMT, note that Beijing time is GMT +. Therefore, the actual time displayed on the webpage is
Add 8 decimal places on the basis of this time, that is
Wed, 3 Apr
2013 12:11:02 GMT
See the figure.
XML file:
Webpage display:
Obviously, the time difference is 8 hours.
Okay. The problem is explained. Here is the solution.
Simply add the code.
NSString* string = @"Wed, 3 Apr 2013 04:11:02 GMT"; NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init]; [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]]; [inputFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"]; NSDate* inputDate = [inputFormatter dateFromString:string]; NSLog(@"date = %@", inputDate); NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init]; [outputFormatter setLocale:[NSLocale currentLocale]]; [outputFormatter setDateFormat:@"HH:mm:ss"]; NSString *str = [outputFormatter stringFromDate:inputDate]; NSLog(@"testDate:%@", str);
Output result:
2013-04-03 12:52:53.714 date[410:303] date = 2013-04-03 04:11:02 +00002013-04-03 12:52:53.718 date[410:303] testDate:12:11:02
The following is a brief explanation.
1. First, generate a formatter corresponding to wed, 3 Apr 2013 04:11:02 GMT format, and then use this formatter to convert the string to date type data. Corresponds to the first program.
2. Generate a formatter that you want to get the time format. Use this formatter to convert the date data to the string type (that is, the desired time format ). Corresponds to the second program.
3. You may see locale above. What is this? According to the online materials, wed cannot be identified to adapt to the Chinese language environment. This is probably the meaning. You can try to comment out the two locale statements.
The format of iOS-nsdateformatter is described as follows:
G: The age of the public, for example, ad yy: the last two digits of the year YYYY: full year mm: Month, displayed as 1-12 Mmm: Month, displayed as short as the English month, for example, Jan mmmm: month, which is the full name of the English month, for example, janualy DD: Day, 2 digits, for example, 02 D: Day, 1-2 digits, for example, 2 EEE: the day of the week, for example, Sun eeee: the day of the week, for example, Sunday AA: Upper afternoon, am/pm h: hour, 24-hour, 0-23 K: hour, 12-hour, 0-11 M: minute, 1-2mm: minute, 2-bit s: Second, 1-2-bit SS: Second, 2-bit s: millisecond Z: GMT
Common time formats include:
yyyy-MM-dd HH:mm:ss.SSSyyyy-MM-dd HH:mm:ssyyyy-MM-ddMM dd yyyy