簡體   English   中英

從NSDate獲取NSDate隨時區調整

[英]Get NSDate from NSDate adjusted with timezone

我有一個NSDate對象。 我們說它代表“1-10-2011”

NSDate *date = [df dateFromString:@"2011-10-01 00:00:00"];

由於我的時區,該日期轉換為“2011-09-30 22:00:00”。

問題:如何在當地時區獲得表示“2011-10-01 00:00:00”的新Date對象?

NSDate僅代表絕對時間點 它沒有時區或日歷的概念。 創建NSDate實例時,自2001年1月1日格林威治標准時間起,它只是幾秒鍾! 如果你在紐約,東京,巴塞羅那或耶路撒冷都沒關系。

在您的示例中,您基於GMT實例化NSDate,但[date description] (在NSLog )將其轉換為您當地的時間。 你有不匹配的地方。

因此,有兩個部分需要考慮:

1.使用NSCalendar和NSTimeZone創建NSDate

如果您手動創建日期,則應指定日歷(2012年格里高利語,但5772格式希伯來語)和時區(倫敦時間晚上22點,但悉尼時間早上7點)。

// Use the user's current calendar and time zone
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone: [NSTimeZone systemTimeZone]];

// Specify the date components manually (year, month, day, hour, minutes, etc.)
NSDateComponents *timeZoneComps=[[NSDateComponents alloc] init];
[timeZoneComps setHour:22];
[timeZoneComps setMinute:0];
[timeZoneComps setSecond:0];
// ... year, month, ...

// transform the date compoments into a date, based on current calendar settings
NSDate *date = [calendar dateFromComponents:timeZoneComps];

此時,日期存儲表示當前日歷的確切時間點(以秒為單位)。

2.使用NSDateFormatter輸出NSDate

對於NSDate的受控輸出 ,您需要NSDateFormatter ,用於將日期轉換為字符串。

基於Apple NSDateFormatter類參考文檔

您可以在樣式日期格式器上獲取和設置許多屬性,但是,我們鼓勵您不要更改個別設置 相反,您應該接受在初始化時建立的默認設置,並使用setDateStyle:,setTimeStyle 指定格式

這對於輸出特別重要,輸出對於每個語言環境都是不同的。 默認情況下,NSDateFormatter會觀察當前用戶的區域設置。 所以相同的NSDate可能是22.11.2011 18:33:19 ,或Nov 22, 2011 6:33:19 PM 2011-11-22 下午6:33:19 ,或2011-11-22 下午6:33:19甚至२२-११-२०११ ६:३३:१९ अपराह् ,全部用於相同的輸入和相同的代碼。

和代碼:

//  NSDate *date -> NSString *dateString 

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];

// Medium style date, short style time => "Nov 23, 1937 3:30pm"
NSString *dateString = [dateFormatter stringFromDate:date];

或者您可以使用類方法localizedStringFromDate對其進行轉換:dateStyle:timeStyle:

我希望這能澄清這個問題。

[NSDate date]以GMT [NSDate date]返回日期。

當你聲明:

由於我的時區,該日期轉換為“2011-09-30 22:00:00”。

是來自NSLog還是NSDateFormatter 不要依賴NSLog使用的[date description] ,它會考慮您的本地時區,使用NSDateFormatter NSDateFormatter有一個setTimeZone方法。

來自[date description]上的Apple文檔:

不保證表示在操作系統的不同版本中保持不變。 要格式化日期,您應該使用日期格式化程序對象

暫無
暫無

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

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