ios 将 GMT NSDate 转换为设备的当前时区

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18107782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:38:34  来源:igfitidea点击:

Convert GMT NSDate to device's current Time Zone

iphoneiosobjective-cparse-platform

提问by Oscar Swanros

I'm using Parse.com to store some values:

我正在使用 Parse.com 来存储一些值:

enter image description here

在此处输入图片说明

These are GMT values. How do I convert these to the device's current time zone and get NSDate as a result?

这些是 GMT 值。如何将这些转换为设备的当前时区并获得 NSDate 结果?

回答by Sam

NSDate is always represented in GMT. It's just how you represent it that may change.

NSDate 始终以 GMT 表示。只是你表达它的方式可能会改变。

If you want to print the date to label.text, then convert it to a string using NSDateFormatterand [NSTimeZone localTimeZone], as follows:

如果要将日期打印到label.text,请使用NSDateFormatterand将其转换为字符串[NSTimeZone localTimeZone],如下所示:

NSString *gmtDateString = @"08/12/2013 21:01";

NSDateFormatter *df = [NSDateFormatter new];
[df setDateFormat:@"dd/MM/yyyy HH:mm"];

//Create the date assuming the given string is in GMT
df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDate *date = [df dateFromString:gmtDateString];

//Create a date string in the local timezone
df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:[NSTimeZone localTimeZone].secondsFromGMT];
NSString *localDateString = [df stringFromDate:date];
NSLog(@"date = %@", localDateString);

// My local timezone is: Europe/London (GMT+01:00) offset 3600 (Daylight)
// prints out: date = 08/12/2013 22:01

回答by Sendoa

The easiest method I've found is this:

我发现的最简单的方法是这样的:

NSDate *someDateInUTC = …;
NSTimeInterval timeZoneSeconds = [[NSTimeZone localTimeZone] secondsFromGMT];
NSDate *dateInLocalTimezone = [someDateInUTC dateByAddingTimeInterval:timeZoneSeconds];

回答by Maria

This is a very clean way to change the NSDate to a local time zone date

这是将 NSDate 更改为本地时区日期的一种非常干净的方法

extension NSDate {

    func toLocalTime() -> NSDate {

        let timeZone = NSTimeZone.local

        let seconds : TimeInterval = Double(timeZone.secondsFromGMT(for:self as Date))

        let localDate = NSDate(timeInterval: seconds, since: self as Date)
        return localDate
    }
}

taken from https://agilewarrior.wordpress.com/2012/06/27/how-to-convert-nsdate-to-different-time-zones/

取自https://agilewarrior.wordpress.com/2012/06/27/how-to-convert-nsdate-to-different-time-zones/

回答by Golden Thumb

Creating an Xcode test case like the following may help us remember the rules "forever":

创建一个像下面这样的 Xcode 测试用例可以帮助我们“永远”记住规则:

- (void)test2015_05_23_07_07_07_Toronto {
    NSString *utcDateString = @"2015_05_23 12:07:07";
    NSDateFormatter *dateFormatter = [NSDateFormatter new];
    dateFormatter.dateFormat = @"yyyy_MM_dd HH:mm:ss";

    dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    NSDate *date2015_05_23_12_07_07_UTC = [dateFormatter dateFromString:utcDateString];

    XCTAssertTrue([date2015_05_23_12_07_07_UTC.description isEqualToString:@"2015-05-23 12:07:07 +0000"]);

    dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"EST"];
    NSString *torontoDateString = [dateFormatter stringFromDate:date2015_05_23_12_07_07_UTC];
    XCTAssertTrue([torontoDateString isEqualToString:@"2015_05_23 07:07:07"]);

    // change format to add ZZZ
    dateFormatter.dateFormat = @"yyyy_MM_dd HH:mm:ss ZZZ";
    torontoDateString = [dateFormatter stringFromDate:date2015_05_23_12_07_07_UTC];
    XCTAssertTrue([torontoDateString isEqualToString:@"2015_05_23 07:07:07 -0500"]);

    XCTAssertEqual(1432382827, [date2015_05_23_12_07_07_UTC timeIntervalSince1970]);

    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
    calendar.timeZone = [NSTimeZone timeZoneWithName:@"EST"];
    NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:date2015_05_23_12_07_07_UTC];
    XCTAssertEqual(2015, components.year);
    XCTAssertEqual(5, components.month);
    XCTAssertEqual(23, components.day);
    XCTAssertEqual(7, components.hour);
    XCTAssertEqual(7, components.minute);
    XCTAssertEqual(7, components.second);
}

回答by NSMutableString

You could use a NSDateFormatter to achieve this result.

您可以使用 NSDateFormatter 来实现此结果。

NSString *dateAsString = @"08/07/2013 04:06";

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"dd/MM/yyyy HH:mm"];

NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[df setTimeZone:gmt];

NSDate *myDate = [df dateFromString: dateAsString];

NSLog(@"date: %@", myDate);

回答by Aaron

There are many answers to this question but I would recommend this one:

这个问题有很多答案,但我推荐这个:

Convert GMT NSDate to device's current Time Zone

将 GMT NSDate 转换为设备的当前时区

NSString *dateStr = @"2012-07-16 07:33:01";
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init]; 
[dateFormatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
NSDate *date = [dateFormatter1 dateFromString:dateStr];
NSLog(@"date : %@",date);

NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone]; // <- Local time zone
NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];

NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date1];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:date1];
NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;

NSDate *destinationDate = [[[NSDate alloc] initWithTimeInterval:gmtInterval    sinceDate:date1] autorelease];

NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
[dateFormatters setDateFormat:@"dd-MMM-yyyy hh:mm"];
[dateFormatters setDateStyle:NSDateFormatterShortStyle];
[dateFormatters setTimeStyle:NSDateFormatterShortStyle];
[dateFormatters setDoesRelativeDateFormatting:YES];
[dateFormatters setTimeZone:[NSTimeZone systemTimeZone]];  
dateStr = [dateFormatters stringFromDate: destinationDate];
NSLog(@"DateString : %@", dateStr);