iOS - Converting time and date to user time zone

前端 未结 2 1054
眼角桃花
眼角桃花 2021-01-03 13:27

I am sending some requests on a webserver that replies me time and date like this:

\"at 18:58 of 05/08/2012\"

I can figure out how to get t

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-03 13:52

    You should do it the following way:

    1) First, create an NSDateFormatter to get the NSDate sent from the server:

    NSDateFormatter *serverFormatter = [[NSDateFormatter alloc] init];
    [serverFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
    [serverFormatter setDateFormat:@"'at 'HH:mm' of 'dd/MM/yyyy"];
    

    From Apple docs: note with the Unicode format string format, you should enclose literal text in the format string between apostrophes ('').

    2) Convert the string (consider it is defined as theString) to a NSDate:

    NSDate *theDate = [serverFormatter dateFromString:theString];
    

    3) Create an NSDateFormatter to convert theDate to the user:

    NSDateFormatter *userFormatter = [[NSDateFormatter alloc] init];
    [userFormatter setDateFormat:@"HH:mm dd/MM/yyyy"];
    [userFormatter setTimeZone:[NSTimeZone localTimeZone]];
    

    3) Get the string from the userFormatter:

    NSString *dateConverted = [userFormatter stringFromDate:theDate];
    

提交回复
热议问题