26
23

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 で日本語の曜日名を取得したい

Last updated at Posted at 2015-09-24

日本語の曜日名を取得する方法を紹介します。

曜日の取得

Swift の場合、曜日は日曜始まりの 1 から 7 の数値で表現されます。

let date: NSDate = NSDate()
let cal: NSCalendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
let comp: NSDateComponents = cal.components(
    [NSCalendarUnit.Weekday],
    fromDate: date
)
let weekday: Int = comp.weekday

曜日名の取得

曜日名のラベルは、NSDateFormatter クラスの shortWeekdaySymbols もしくは weekdaySymbols プロパティから配列として取得することができます。
その配列の添字の 0 - 6 が日曜から始まる曜日に該当します。

そして、日本語で曜日名を取得する場合は、NSDateFormatter のローケルを設定するだけです。

let weekdaySymbolIndex: Int = weekday - 1
let formatter: NSDateFormatter = NSDateFormatter()

formatter.locale = NSLocale(localeIdentifier: "ja")

print(formatter.shortWeekdaySymbols[weekdaySymbolIndex]) // -> 日

print(formatter.weekdaySymbols[weekdaySymbolIndex]) // -> 日曜日

26
23
1

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
26
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?