2012-07-26 36 views

Trả lời

23

này nên làm những gì bạn cần:

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); 

Lưu ý rằng ví dụ của bạn không chính xác: khi đó là 1 giờ sáng vào ngày 6 đến ngày 14 tháng 6 ở UTC, nó vẫn là ngày 6 tháng 6 trong EST, 8 giờ tối thời gian tiết kiệm ánh sáng ban ngày và h.đa. Trên hệ thống của tôi chương trình này in

Jun 13, 2012 - 21:00:00 EDT 
2

chuyển đổi này từ giờ GMT Giờ địa phương, bạn có thể sửa đổi nó một chút cho 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]; 

Taken từ iPhone: NSDate convert GMT to local time

4
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]; 
2

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: Ngày mở rộng UTC hoặc giờ ⟺ 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) 
    } 

} 
Các vấn đề liên quan