Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to convert NSDate from local timezone to UTC and vice versa in objc

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 3.98k
    Comment on it

    1. To convert UTC to local time zone

    - (NSString *)convertLocalDateFromUTCDate:(NSString *)dateStr{
        NSDateFormatter *formatter = [self dateFormatter];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
        NSDate *sourceDate = [formatter dateFromString:dateStr];
        NSDateFormatter* dateFormat = [self dateFormatter];
        [dateFormat setDateFormat:@"MMM dd @hh:mm aa"];
        NSString* localTime = [dateFormat stringFromDate:sourceDate];
        return [NSString stringWithFormat:@"%@",localTime];
    }
    
    - (NSDateFormatter *)dateFormatter
    {
        static NSDateFormatter *formatter;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            formatter = [NSDateFormatter new];
        });
        return formatter;
    }
    
    

    2. To convert local time zone to UTC

    -(NSString *)convertUTCDateFromLocalDate:(NSString *)utcDateStr
    {
        NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"MMM dd @hh:mm aa"];
        NSTimeZone *utc = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
        [formatter setTimeZone:utc];
        [formatter setDateFormat:@"MMM dd @hh:mm aa"];
        NSDate *localDate = [formatter dateFromString:utcDateStr]; // get the date
        NSTimeInterval timeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT]; // You could also use the systemTimeZone method
        NSTimeInterval utcTimeInterval = [localDate timeIntervalSinceReferenceDate] - timeZoneOffset;
        NSDate *utcCurrentDate = [NSDate dateWithTimeIntervalSinceReferenceDate:utcTimeInterval];
        return [formatter stringFromDate:utcCurrentDate];
    }
    
    

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: