在iOS中转换系统时区中的任何时区日期 [英] Convert any timezone date in system timezone in iOS

查看:130
本文介绍了在iOS中转换系统时区中的任何时区日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将给定日期转换为iOS中的系统时区时,我遇到了问题.

I am facing problem while converting given date into system time zone in iOS.

来源日期:2013-03-18 03:54:18//其采用AM格式 目的地日期应为:2013-03-18 03:30:15//以PM格式.

Source date: 2013-03-18 03:54:18 // its in AM format Destination date should be : 2013-03-18 03:30:15 //its in PM format.

我怎么能得到这个??

How can I get this??

我尝试了下面的代码,但数据和差异也有所不同.

I have tried below code but getting wrong data and difference too.

NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSLog(@"Post date::%@",postDate);
NSDate *utc = [fmt dateFromString:postDate];
fmt.timeZone = [NSTimeZone systemTimeZone];
NSString *local = [fmt stringFromDate:utc];
NSLog(@" local %@", local);

NSDate *date1 = [NSDate date];
NSString *currentDateString = [fmt stringFromDate:date1];
NSDate *currentDate = [fmt dateFromString:currentDateString];
NSUInteger flags = NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:utc toDate:currentDate options:0];
NSLog(@"difference::%d",[difference day]);
NSLog(@"difference::%d",[difference hour]);
NSLog(@"difference::%d",[difference minute]);

编辑:输出

Post date::2013-03-18 03:20:09 
local 2013-03-18 03:20:09 
difference::0 
difference::13 
difference::2

推荐答案

NSString *openingHour = @"15:05:35 ";
 NSDateFormatter *workingHoursFormatter = [[NSDateFormatter alloc] init]; 
        NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
        [workingHoursFormatter setTimeZone:timeZone];
        [workingHoursFormatter setDateFormat:@"HH:mm"];
        NSDate *openingTime = [workingHoursFormatter dateFromString:openingHour];

您可以尝试上述代码对我有用吗,根据需要更改日期格式

Can you try the above code it works for me , alter the date format to your need

这篇关于在iOS中转换系统时区中的任何时区日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆