Convert UTC to local time with NSDateFormatter

后端 未结 3 1723
悲哀的现实
悲哀的现实 2020-12-05 03:24

I am getting the following string from a server in my iOS app:

20140621-061250

How can I convert it to the local time?

3条回答
  •  情话喂你
    2020-12-05 04:19

    To get your string into a NSDate, you would use a NSDateFormatter like this:

    NSString *myDateAsAStringValue = @"20140621-061250"
    NSDateFormatter *df = [[NSDateFormatter alloc] init];    
    [df setDateFormat:@"yyyyMMdd-HHmmss"];
    NSDate *myDate = [df dateFromString: myDateAsAStringValue];
    

    You may want to read this post about working with Date and Time

    EDIT:

    To parse it as UTC you have to add the line:

    [df setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    

    Also, when you print it with NSLog, if you are using the same NSDateFormatter, you will get the input string as output (since you apply the inverse of the parsing function).

    Here is the full code, for parsing and for getting the output with a standard format:

    //The input
    NSString *myDateAsAStringValue = @"20140621-061250";
    
    //create the formatter for parsing
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    [df setDateFormat:@"yyyyMMdd-HHmmss"];
    
    //parsing the string and converting it to NSDate
    NSDate *myDate = [df dateFromString: myDateAsAStringValue];
    
    //create the formatter for the output
    NSDateFormatter *out_df = [[NSDateFormatter alloc] init];
    [out_df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssz"];
    
    //output the date
    NSLog(@"the date is %@",[out_df stringFromDate:myDate]);
    

提交回复
热议问题