简体   繁体   中英

How to get the UTC time from NSDate iOS

I want to log the server time in my iOS app , I am using NHNetworkTime library to get the network time, when I try to print the following code its showing GMT, through I have chosen UTC, how to print the date time in 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 

There is no time difference between Coordinated Universal Time (UTC) and Greenwich Mean Time(GMT). you can get more info from here More info

Refer :-

-(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;
}

Moreover to get time

-(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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM