5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift:NSDateの年号を西暦表示

Posted at

OSX El Capitan(10.11.6)
Xcode 7.3.1
Swift version 2.2
を使用しております。

iPhoneの設定で書式の暦法を和暦に設定していると
([設定]→[一般]→[言語と地域]→書式)
下記のようなプログラムを書いた場合

let date:NSDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss" // 日付フォーマットの設定
        
print(dateFormatter.stringFromDate(date))

--結果--
0028/08/14 23:54:16

年号のところが0028と和暦で取得され表示されます。
システムで設定したものが使われるようです。

西暦で取得したい場合、カレンダー設定することにより暦法を変更することができます。

let date:NSDate = NSDate()
let dateFormatter = NSDateFormatter()
//カレンダー設定
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)

dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss" // 日付フォーマットの設定
dateFormatter.calendar = calendar //フォーマットにカレンダー設定
                
print(dateFormatter.stringFromDate(date))

--結果--
2016/08/14 23:55:36

きちんと設定するとシステムに影響されることなく取得できます。

5
4
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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?