Recently in doing Sina RSS news XML parsing process, encountered a time string conversion problem.
The problem is: Wed, 3 APR 2013 04:11:02 GMT (this data is obtained in an XML file) to intercept 04:11:02 in this string.
Note: The GMT should pay special attention to the Beijing time is gmt+8:00 so the actual time on the page page is to add 8 decimal on the basis of this time, which is
Wed, 3 APR 2013 12:11:02 GMT
Just look at the picture, okay?
XML file:
Page display:
Obviously the time difference is 8 hours.
Well, that explains the problem, and here's how it's done.
Just go straight to the code.
[CPP] View plain copy <span style= "White-space:pre" > </span>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 results:
[CPP] view plain copy 2013-04-03 12:52:53.714 date[410:303] date = 2013-04-03 04:11:02 +0000 2013-04-03 12:5 2:53.718 date[410:303] Testdate:12:11:02
let's explain a little bit below.
1, the first is to generate a corresponding to the Wed, 3 APR 2013 04:11:02 GMT Format formatter, and then use this formatter to convert this string to date type data. Corresponds to the first paragraph of the procedure.
2, and then generate a formatter of the time format you want to get, and use this formatter to convert this date data to string type (the time format you want). corresponding to the second section of the procedure.
3, the above may see locale, this is what to do. According to the information on the Internet is to adapt to the Chinese environment, or will not recognize the wed such, if the English environment is not necessary. That's probably what it means. You can try to comment out these two locale statements, found that really can not oh.
Here are the Ios-nsdateformatter format descriptions:
[CPP] view plain copy G: A.D., for example ad yy: Year after 2-bit yyyy: Full year MM: month, displayed as 1-12 MMM: month, shown as the English month abbreviation, such as the first time MMMM: month, displayed as the English month full name, such as Janualy DD: day, 2 digits, such as D: Day, 1-2-bit display, such as 2 EEE: abbreviated days of the week, such as Sun eeee: All the days of the week, such as Sunday AA: On the afternoon, am/pm H: When 2 4-hour system, 0-23 K: When, 12-hour system, 0-11 m: Min, 1-2 mm: minutes, 2 S: seconds, 1-2-bit ss: sec, 2-bit s: Ms Z:gmt
The usual time formats are:
[CPP] view plain copy yyyy-mm-dd HH:mm:ss. SSS yyyy-mm-dd HH:mm:ss yyyy-mm-dd MM DD yyyy