In iOS if you use [NSDate Date] to get the time, it is not possible, because this time is GMT time, that is, GMT, and Beijing time is 8 hours, then how to get the standard time? There are two ways to do this.
①, using formatter to format time
Code implementation:
1 NSDateFormatter *form = [[NSDateFormatter alloc] init]; 2 [Form Setdateformat:@ "mm-dd-hh-mm"]; 3 NSString *str = [Form stringfromdate:date];
②, plus 8 hours on the GMT time basis
1 NSDate *date = [NSDate date]; 2 Nstimezone *zone = [Nstimezone systemtimezone]; 3 Nsinteger interval = [zone secondsfromgmtfordate:date]; NSDate *nowdate = [date Datebyaddingtimeinterval:interval];
It is important to note that if you use the second method to get time, you can no longer use format for formatting time, and if you do that, it will be 8 hours apart from the current time!
Code to test:
1 //Get Standard Time2NSDate *date =[NSDate Date];3NSLog (@"time taken directly with NSDate:%@", date);4 //time after formatting with formatter5NSDateFormatter *formatter =[[NSDateFormatter alloc] init];6[Formatter Setdateformat:@"YYYY-MM-DD Hh-mm-ss"];7NSString *time_now =[Formatter stringfromdate:date];8NSLog (@"time%@ after formatting", Time_now);9 //Add 8 hours of time to GMTTenNstimezone *zone =[Nstimezone Systemtimezone]; OneNsinteger sec =[Zone secondsfromgmtfordate:date]; ANSDate *new_date =[Date datebyaddingtimeinterval:sec]; -NSLog (@"time after adding a time difference to GMT:%@", new_date); - the //time is error if you format it after the time difference is added. -NSString *time_other =[Formatter stringfromdate:new_date]; -NSLog (@"Add a time difference after the format:%@", Time_other);
Printing results:
1 .- to- + -: About:42.593ttttt[2206:156343] The time obtained directly using nsdate: .- to- + the: About: the+00002 .- to- + -: About:42.594ttttt[2206:156343] Time after formatting 2016- to- + -- About- the3 .- to- + -: About:42.594ttttt[2206:156343] The time after the GMT time is added: .- to- + -: About: the+00004 .- to- + -: About:42.594ttttt[2206:156343] plus the time difference after the format: .- to- A on- About- the
Can see the problem exists!
Transferred from: http://www.lrdup.net/archives/1042
Get Standard Time in iOS (reprint)