swift 4 current year, month, day
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.
Related protips:
Some simple Swift Extensions (Strip HTML, RGB Color, Color invert, Dismiss modal segue)
Written by kanshuYokoo
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Swift
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#