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)