LoginSignup
0
0

More than 1 year has passed since last update.

Swift Date関連の備忘録

Last updated at Posted at 2023-02-01

Swiftで曜日を表示する

yyyy/MM/dd(EEE)
DateFormatterから曜日のフォーマットを指定して表示することができるようにする。
Apple DateFormatter

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd(EEE)"
let date = dateFormatter.string(from: Date())

冗長だけど、、、
DateFormatterから曜日を取得できることを知る前は、以下のように取得していた。
Apple CalendarComponet

let weekDay = Calendar.current.component(.weekday, from: Date()) - 1
switch weekDay {
case 1:
    result = "(月)"
case 2:
    result = "(火)"
case 3:
    result = "(水)"
case 4:
    result = "(木)"
case 5:
    result = "(金)"
case 6:
    result = "(土)"
case 7,0:
    result = "(日)"
default:
    result = ""
}

Swiftで月初、月末を表示する

特定の日から、月初、月末を算出したい場合は、from: Date()の部分を置き換えれば良い。

月初

let calendar = Calendar(identifier: .gregorian) 
let dateComponents = calendar.dateComponents([.year, .month], from: Date())
let beginMounth = calendar.date(from: dateComponents)!

月末

let add = DateComponents(month: 1, day: -1)
let endMonth = calendar.date(byAdding: add, to: beginMounth)!
0
0
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
0
0