Swift - Get local date and time

前端 未结 10 653
挽巷
挽巷 2020-12-17 08:51

How can I get local date and time in Swift?

let last_login = String(NSDate.date())
相关标签:
10条回答
  • 2020-12-17 09:35

    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
    
    0 讨论(0)
  • 2020-12-17 09:36

    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)
    
    0 讨论(0)
  • 2020-12-17 09:39
    let expiryDate: Date = ...
    let localizedDateString = DateFormatter.localizedString(from: expiryDate, dateStyle: .medium, timeStyle: .short)
    

    "10 Sep 2017, 14:37"

    0 讨论(0)
  • 2020-12-17 09:39

    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
    
    0 讨论(0)
提交回复
热议问题