Get the time and date of selected time zone?

前端 未结 2 772
栀梦
栀梦 2020-12-22 05:41

I tried below snippet I\'m getting current date and time of system instead of the selected time zone code.

NSDate *now = [NSDate date];
NSCalendar *gregorian         


        
相关标签:
2条回答
  • 2020-12-22 06:22

    [NSDate date]returns a date object representing the current date and time, no matter where you are. NSDates are not subject to places or time zones. There is just one NSDate that represents now or any other moment for that matter, not different date objects for every time timezone. Therefore, you should not attempt to convert a date between time zones.

    NSDate objects represent an absolute instant in time. Consider the following example of how two date representations in different time zones (9/9/11 3:54 PM in Paris and 9/9/11 11:54 PM in Sydney) are actually the same date.
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterShortStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Europe/Paris"]];
        NSDate *aDate = [formatter dateFromString:@"9/9/11 3:54 PM"];
        [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Australia/Sydney"]];
        NSDate *anotherDate = [formatter dateFromString:@"9/9/11 11:54 PM"];
        NSLog(@"%@",anotherDate);
        if ([aDate isEqualToDate:anotherDate]) {
            NSLog(@"How about that?");
        }
    

    When it comes to output a date, bear in mind that NSDate's description method returns time in GMT and you need to use a NSDateFormatter to create a date string representing the local time in Paris, Sydney, etc. from a date:

    NSDate *now = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterShortStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Australia/Sydney"]];
    NSLog(@"%@",[formatter stringFromDate:now]); //--> 9/9/11 11:54 PM
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Europe/Paris"]];
    NSLog(@"%@",[formatter stringFromDate:now]); //-->  9/9/11 3:54 PM
    
    0 讨论(0)
  • 2020-12-22 06:47
    [dateFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss z"];
    

    Remove the trailing 'z' character from the format string if you don't want to display the time zone.

    EDIT

    On the other hand, if you just want to display the timezone name, just make the 'z' uppercase.

    EDIT

    Lowercase 'z' works fine for all the other timezones, but unfortunately GMT is a special case. So the easiest thing to do is to just omit the 'z' and append " GMT" to the formatted date.

    0 讨论(0)
提交回复
热议问题