current year, month, day

current year, month, day. swift 4 

to get current date in the format "yyyy-MM-dd HH:mm:ss"
let date = Date()
let format = DateFormatter()
format.dateFormat = "yyyy-MM-dd HH:mm:ss"
let formattedDate = format.string(from: date)
print(formattedDate)
if you need current day, month, year.
use Calendar class
let calendar = Calendar.current
calendar.component(.year, from: date)
calendar.component(.month, from: date)
calendar.component(.day, from: date) 
all returns int. if the moth is September .month would return 9.
day of week.
calendar.component(.weekday, from: date)
It will return 1 when it is in Sunday as in Gregorian Calendar.
add month
var lastMonthDate = Calendar.current.date(byAdding: .month, value: -1, to: date)
calendar.component(.month, from:lastMonthDate!)
it gives you the number of last month.

0 件のコメント:

コメントを投稿