簡體   English   中英

獲取目標中當前時區的日期-C?

[英]Get date in current time zone in objective - c?

NSArray *fromD = [setFreeHour valueForKey:@"fromDate"];
NSString *fromdate = fromD[0];
NSDateFormatter *fromDateFormatter = [[NSDateFormatter alloc]init];

[fromDateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *fromDate = [fromDateFormatter dateFromString:fromdate];

結果:

  • 在fromdate = 2018-07-24 11:41:25

  • 在fromDate = 2018-07-24 06:11:25 +0000

所以我如何才能使本地時區中的日期(fromdate和fromDate)相等或fromDate

NSDate值表示一個時間點,而與該點的本地解釋NSDate ,即,當您在中午時分,在其他地方的午夜時分–同一時間點,不同的本地解釋。

因此,當比較日期時,首先將它們轉換為等效的NSDate表示形式。

要將文本格式的日期/時間轉換為NSDate格式,請使用NSDateFormatter 如果沒有以您使用的文本格式指定時區,或者您設置了formatters時區屬性,則您的NSDateFormatter實例將使用在其運行的計算機上設置的當前本地時區。 例如,如果您的代碼的文本格式與NSDate值之間的時間差為5小時,那么我們可以推斷出您使用的計算機位於當地時間UTC / GMT之前5小時

我需要比較這些日期。 那么我怎樣才能使兩個日期相等呢?

您可以按照自己的方式做,將文本格式轉換為NSDate值,然后使用NSDate提供的方法比較這些值。 那就是您沒有“使兩者相等”,而是將每個轉換為時間點並進行比較。

高溫超導

順便說一句:建議不要使用fromDate不同的變量名fromdatefromDate ,這會使代碼難以閱讀,調試和維護。

問題后編輯

您已編輯問題,以進一步詢問如何在本地時區顯示NSDate fromDate 答案與將文本格式轉換為NSDate -使用NSDateFormatter, indeed you can use the exact same one. Insteading of using the method格式NSDateFormatter, indeed you can use the exact same one. Insteading of using the method NSDateFormatter, indeed you can use the exact same one. Insteading of using the method you used to get from text format you use NSDateFormatter, indeed you can use the exact same one. Insteading of using the method dateFromString:, you used to get from text format you use stringFromDate:`轉換為文本格式。 上述關於時區的相同規則適用。

如果僅使用NSLog()一個NSDate值,您將獲得它在UTC / GMT中表示的時間點。

暫無
暫無

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

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