簡體   English   中英

如何從NSDate iOS獲取UTC時間

[英]How to get the UTC time from NSDate iOS

我想在我的iOS應用中記錄服務器時間,我正在使用NHNetworkTime庫獲取網絡時間,當我嘗試打印以下顯示GMT的代碼時,通過選擇UTC,如何在UTC中打印日期時間?

NSDate* datetime = [NSDate networkDate];
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; // Prevent adjustment to user's local time zone.
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS Z z "];
    NSString* dateTimeInIsoFormatForZuluTimeZone = [dateFormatter stringFromDate:datetime];

NSLog(@"%@",dateTimeInIsoFormatForZuluTimeZone);

this is printing 2016-03-09 06:51:23.406 +0000 GMT 

協調世界時(UTC)和格林威治標准時間(GMT)之間沒有時差。 您可以從這里獲取更多信息更多信息

參考:-

-(NSString *)getUTCFormateDate:(NSDate *)localDate
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    [dateFormatter setTimeZone:timeZone];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:localDate];
    [dateFormatter release];
    return dateString;
}

而且要有時間

-(NSString *)getTimeFromDate:(NSDate *)localDate
{
    NSDateFormatter *dateFormatter = [[[NSDateFormatter     alloc]init]autorelease];
    dateFormatter.dateFormat = @"MM/dd/yy";

    NSString *dateString = [dateFormatter stringFromDate: localDate];

    NSDateFormatter *timeFormatter = [[[NSDateFormatter alloc]init]autorelease];
    timeFormatter.dateFormat = @"HH:mm:ss";
    return [timeFormatter stringFromDate: localDate];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM