LoginSignup
11
7

More than 5 years have passed since last update.

NSDateFormatter / 日付フォーマットについて

Last updated at Posted at 2014-06-28

Unicode Technical Standard #35 Unicode Locale Data Markup Language

日付表記の RFC 3339 とか ISO 8601 とかなんかあれ系のやつ。
それぞれの規格の区別は正直よくわからないが、NSDateFormatter は Unicode の規格に対応している。

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW13

表記

年月日

yyyy-MM-dd
例:2014-06-29

年月日T時分秒および時間帯

yyyy-MM-ddTHH:mm:ssZ
例:2014-06-29T18:20:46+0900

二桁の年

yy
例:14

大文字の YYYY

その日が木曜日〜土曜日なら、前年の週とみなす。
年が明けたのに前年の表記になる可能性があるので、日本の文化的には小文字を使った方が良いかもしれない。

ミリ秒

S
例:12.678 → ss.SSS

+09:00 のようなコロン区切りの時間帯表記

ISO8601 の表記法で、WebAPI でよく使われる。これは ZZZZZ で対応できるらしい。
http://www.unicode.org/reports/tr35/tr35-25.html#Date_Format_Patterns

和暦

G で元号表示できる。
例:GGyy/MM/dd HH:mm:ss → 平成28年/00/00 23:59:59

let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale.currentLocale()

if NSCalendar.currentCalendar().calendarIdentifier == NSCalendarIdentifierJapanese {
    // 元号表示
    dateFormatter.dateFormat = "GGyy/MM/dd HH:mm:ss"
}
else {
    // 西暦表示
    dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss"
}

[rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
NSString *dateString = @"Sun, 29 Jun 2014 06:34:30 +0900";
[formatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZZ"];

''は無くてもたぶん動く。

参考文献

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1
http://www.kanzaki.com/docs/html/dtf.html#w3cdtf
http://www.unicode.org/reports/tr35/
http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns

Date Format を即席で検証するときに便利

http://nsdateformatter.com
※ZZZZZ には対応していない

W3C 表記に対応する場合など

[iOS][Mac] ISO 8601 相当の日付文字列を NSDateFormatter で変換する
http://cocoadays.blogspot.jp/2011/03/iosmac-iso-8601-nsdateformatter.html

iOS で実装する場合やフォーマットの指定方法など

NSDateFormatter - 文字列と日付の変換
http://d.hatena.ne.jp/nakamura001/20100525/1274802305

日付形式の違い

ISO8601/RFC3339/W3CDTF: 2001-02-03T04:05:06+09:00
RFC2822: Sat, 03 Feb 2001 04:05:06 +0900
ctime: Sat Feb 03 04:05:06 JST 2001

11
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
7