簡體   English   中英

在iOS中轉換系統時區中的任何時區日期

[英]Convert any timezone date in system timezone in iOS

將給定日期轉換為iOS中的系統時區時遇到問題。

原始日期:2013年3月18日03:54:18 //日期為AM格式目的地日期應為:2013-03-18 03:30:15 //其PM格式。

我怎么能得到這個?

我試過下面的代碼,但也得到錯誤的數據和區別。

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

從...替換您的代碼

fmt.timeZone = [NSTimeZone systemTimeZone];

像這樣

fmt.timeZone = [NSTimeZone localTimeZone];

這將為您服務...

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

您可以嘗試上述代碼對我有用嗎,請根據需要更改日期格式

暫無
暫無

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

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