在開發iOS程式時對日期處理的總結

2021-06-14 18:32:51 字數 2534 閱讀 8462

由於ios的裝置對應多國語言,使用者也可以選擇不同的日曆模式。比如日本的和歷,泰國日曆等等。使用者也可以自行設定24小時制或者12小時制來顯示時間。這些設定會直接影響應用程式取得的日期。這篇文章總結一下程式中相關的類和裝置的各種設定的關係。

nscalendar

[nscalendar currentcalendar]

[nscalendar autoupdatingcurrentcalendar]

系統的設定 > 通用 > 多語言環境 > 日曆

上述的日曆設定和nscalendar是有直接關係的。

比如設定成「日本日曆」的時候、currentcalendar的值是nsjapanesecalendar

設定成「公曆」的時候、currentcalendar的值是nsgregoriancalendar

注意:在程式中,currentcalendar取得的值會一直保持在cache中,第一次取得以後如果使用者修改該系統日曆設定,這個值也不會改變。如果用autoupdatingcurrentcalendar,那麼每次取得的值都會是當前系統設定的日曆的值。

系統中定義的日曆有:

nsstring * const nsgregoriancalendar;

公曆(常用)

nsstring * const nsbuddhistcalendar;

佛教日曆

nsstring * const nschinesecalendar;

中國農曆(常用)

nsstring * const nshebrewcalendar;

希伯來日曆

nsstring * const nsislamiccalendar;

伊斯蘭歷

nsstring * const nsislamiccivilcalendar;

伊斯蘭教日曆

nsstring * const nsjapanesecalendar;

日本日曆(和曆,常用)

nsstring * const nsrepublicofchinacalendar;

中華**日曆(台灣)

nsstring * const nspersiancalendar;

波斯歷nsstring * const nsindiancalendar;

印度日曆

nsstring * const nsiso8601calendar;

iso8601(但是現在還不可用)

通過calendar可以設定timezone和locale。

如果你要通過nsdateformatter來設定日期格式,比如」yyyy-mm-dd」等,那需要注意對formatter設定日曆。

如果想要用公曆的時候,就要將nsdateformatter的日曆設定成公曆。否則隨著使用者的系統設定的改變,取得的日期的格式也會不一樣。

nscalendar *calendar =

[[nscalendar alloc]initwithcalendaridentifier:nsgregoriancalendar];

nsdateformatter *formatter = [[nsdateformatter alloc] init];

[formatter setcalendar:calendar];

nslocale

[nslocale currentlocale]

[nslocale systemlocale]

[nslocale autoupdatingcurrentlocale]

nslocale與下面的設定有關:

系統的設定 > 通用 > 多語言環境 > 區域格式

系統的設定 > 通用 > 日期與時間 > 24小時制

根據國家區域的設定的不同,格式也會不一樣,例如:

中國: 「11月」 美國:「november」

中國: 「上午」 美國:「am」

如果你的應用程式在多個國家發布,那你就需要注意設定nslocale。

比如:[[nslocale alloc] initwithlocaleidentifier:@」en_us」]

cunnretlocale是使用者設定的值。

systemlocale是裝置預設的值。

nsdateformatter

理解日期格式的設定非常重要。

有時候會遇到下面的情況:

比如你將格式設定成

@」yyyy-mm-dd hh:mm:ss」

但顯示出來的卻是

「0024-11-16 21:09:17」

(這個時候使用者把日曆設定成了日本日曆)

又或者顯示成

「2012-11-17 下午11:07:47」

(24小時制關閉的時候)

上述的情況如果不考慮到的話,那程式中就會出現bug。

如果將日期的格式的日曆設定成公曆,

nsdateformatter 設定成 nsgregoriancalendar,

需要用24小時制的時候,可以把locale設定成systemlocale。

(如果你沒有特定需要指定的locale的話)

Oracle 的TO DATE對日期處理

用例 select to date 2014 09 03 yyyy mm dd hh24 mi ss as nowtime from dual 1.日期和字元轉換函式用法 to date,to char select to char sysdate,yyyy mm dd hh24 mi ss as ...

在ASP處理程式時顯示進度

過軟體的朋友都知道,進度條是乙個優秀軟體的重要組成部分。它的存在能夠使使用者及時掌握程式的執行進度,確認應用程式正常工作。可是asp 中似乎沒有上述標準控制項,控制起來也比較麻煩。那么如何實現進度條呢?以下是本人的一些觀點 僅供參考 我們通常在用asp 處理程式 指的是寫檔案或運算元據庫 的時候,會...

pandas 對日期型別資料的處理

pandas 的日期 時間型別有如下幾種 concept scalar class array class pandas data type primary creation method date times timestamp datetimeindex datetime64 ns or dat...