[Swift]Calendarで年月日を取得する

書式
let 変数名 = Calendar(identifier: .gregorian)
変数名.component(.year, from: date)
変数名.component(.month, from: date)
変数名.component(.day, from: date)

使用例

import Foundation

let calendar = Calendar(identifier: .gregorian)
let date = Date()
//.yearで年の取得
let year = calendar.component(.year, from: date)
print("年: "+String(year))

//.monthで月の取得
let month = calendar.component(.month, from: date)
print("月: "+String(month))

//.dayで日の取得
let day = calendar.component(.day, from: date)
print("日: "+String(day))

//.hourで時間の取得
let hour = calendar.component(.hour, from: date)
print("時間: "+String(hour))

//.minuteで分の取得
let minute = calendar.component(.minute, from: date)
print("分: "+String(minute))

//.secondで秒の取得
let second = calendar.component(.second, from: date)
print("秒: "+String(second))

結果
$ swift test01.swift
年: 2021
月: 10
日: 6
時間: 10
分: 39
秒: 11

Swift

Posted by arkgame