Подтвердить что ты не робот

Как преобразовать строку даты UTC в локальное время (systemTimeZone)

Строка ввода: 14 июня 2012 г. - 01:00:00 UTC

Выходная локальная строка: 13 июня 2012 г. - 21:00:00 EDT

Мне нравится получать смещение от

NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSLog(@"Time Zone: %@", destinationTimeZone.abbreviation);

Любое предложение?

4b9b3361

Ответ 1

Это должно делать то, что вам нужно:

NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"LLL d, yyyy - HH:mm:ss zzz";
NSDate *utc = [fmt dateFromString:@"June 14, 2012 - 01:00:00 UTC"];
fmt.timeZone = [NSTimeZone systemTimeZone];
NSString *local = [fmt stringFromDate:utc];
NSLog(@"%@", local);

Обратите внимание, что ваш пример неверен: когда он 1 июня 14 июня в UTC, он все еще 13 июня в EST, стандарте 8 вечера или 9 PM летнее время. В моей системе эта программа печатает

Jun 13, 2012 - 21:00:00 EDT

Ответ 2

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"MMMM d, yyyy - HH:mm:ss zzz"; // format might need to be modified

NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
[dateFormatter setTimeZone:destinationTimeZone];

NSDate *oldTime = [dateFormatter dateFromString:utcDateString];

NSString *estDateString = [dateFormatter stringFromDate:oldTime];

Ответ 3

Это преобразование из GMT в местное время, вы можете немного изменить его для UTC Time

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm";

NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; 
[dateFormatter setTimeZone:gmt]; 
NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]]; 
[dateFormatter release];

Взято из iPhone: NSDate конвертирует GMT в местное время

Ответ 4

Swift 3

var dateformat = DateFormatter()
dateformat.dateFormat = "LLL d, yyyy - HH:mm:ss zzz"
var utc: Date? = dateformat.date(fromString: "June 14, 2012 - 01:00:00 UTC")
dateformat.timeZone = TimeZone.current
var local: String = dateformat.string(from: utc)
print(local)


Swift 4: добавление даты UTC или GMT ⟺ Local

//UTC or GMT ⟺ Local 

extension Date {

    // Convert local time to UTC (or GMT)
    func toGlobalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }

    // Convert UTC (or GMT) to local time
    func toLocalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }

}