How can I get local date and time in Swift?
let last_login = String(NSDate.date())
use NSDateFormatter, either by setting the format
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "hh:mm"
println(dateFormatter.stringFromDate(NSDate()))
or styles
dateFormatter.dateStyle = .NoStyle
dateFormatter.timeStyle = .MediumStyle
You have to use NSDateFormatter
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMMM dd, yyyy HH:mm"
dateFormatter.locale = "en" // Change "en" to change the default locale if you want
let stringDate = dateFormatter.stringFromDate(date)
let expiryDate: Date = ...
let localizedDateString = DateFormatter.localizedString(from: expiryDate, dateStyle: .medium, timeStyle: .short)
"10 Sep 2017, 14:37"
Swift 5
If you want to do it manually,
Date() will always return current UTC time
let today = Date()
If you live, let's say in Malaysia. It is UTC+8 (meaning 8 hours faster)
You can get your local date time by using Calendar
let localDateTime = Calendar.current.date(byAdding: .hour, value: 8, today)!
other method you can use is
let localDateTime = Date().addingTimeInterval(8 * 60 * 60) //because the param in seconds