代码之家  ›  专栏  ›  技术社区  ›  Nurdin

Swift-获取本地日期和时间

  •  38
  • Nurdin  · 技术社区  · 10 年前

    如何在Swift中获取本地日期和时间?

    let last_login = String(NSDate.date())
    
    11 回复  |  直到 4 年前
        1
  •  64
  •   Leo Dabus    6 年前

    更新: Xcode 8.2.1 Swift 3.0.2

    也可以使用Date方法 description(with locale: Locale?) 获取用户的本地化时间描述:

    日期的字符串表示,使用给定的区域设置,或者如果区域设置 参数为零,国际格式为YYYY-MM-DD HH:MM:SS ±HHMM,其中±HHMM表示以小时为单位的时区偏移,以及 UTC的分钟数(例如2001-03-24 10:45:32+0600)。

    description(with locale: Locale?)

    Date().description(with: .current)   // "Monday, February 9, 2015 at 05:47:51 Brasilia Summer Time"
    

    上面的方法不打算在向用户显示日期和时间时使用。它仅用于调试目的。

    当向用户显示本地日期和时间(当前时区)时,您应该尊重用户的区域设置和设备设置。唯一可以控制的是日期和时间样式(短、中、长或完整)。有关更多信息,请查看此帖子 shortDateTime .

    如果您的意图是为了编码目的创建UTC时间戳(iso8601),您可以查看这篇文章 iso8601

        2
  •  31
  •   lajosdeme    5 年前

    如果你想得到 日期对象 而不是字符串表示,您可以使用以下代码段:

    extension Date {
        func localDate() -> Date {
            let nowUTC = Date()
            let timeZoneOffset = Double(TimeZone.current.secondsFromGMT(for: nowUTC))
            guard let localDate = Calendar.current.date(byAdding: .second, value: Int(timeZoneOffset), to: nowUTC) else {return Date()}
    
            return localDate
        }
    }
    

    这样使用:

    let now = Date().localDate()
    
        3
  •  10
  •   ScottyBlades    4 年前

    利奥的回答很好。我只是想添加一种将其用作计算属性的方法。

     var currentTime: String { 
         Date().description(with: .current) 
     }
    

    这样使用:

    print(currentTime)
    

    或者您可以封装它:

    extension String { 
        static var currentTime: String { 
            Date().description(with: .current) 
        }
    }
    

    然后,您可以在任何使用字符串的地方使用它:

    var time: String = .currentTime
    
        4
  •  7
  •   vikingosegundo    10 年前

    通过设置格式使用NSDateFormatter

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "hh:mm"
    println(dateFormatter.stringFromDate(NSDate()))
    

    或样式

    dateFormatter.dateStyle = .NoStyle
    dateFormatter.timeStyle = .MediumStyle
    
        5
  •  6
  •   Leo Dabus    10 年前

    我已经找到答案了。

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
    let dateInFormat = dateFormatter.stringFromDate(NSDate())
    
        6
  •  5
  •   Warif Akhand Rishi    7 年前
    let expiryDate: Date = ...
    let localizedDateString = DateFormatter.localizedString(from: expiryDate, dateStyle: .medium, timeStyle: .short)
    

    “2017年9月10日,14:37”

        7
  •  5
  •   trndjc    3 年前

    要恢复最常见的字符串格式(处理查询和数据库时):

    雨燕4、5

    2019-01-09T01:07:04Z (GMT/祖鲁时间的RFC3339)

    let f = ISO8601DateFormatter()
    f.formatOptions = [.withInternetDateTime]
    let s = f.string(from: Date())
    

    2019-01-08 17:04:16-08:00 (RFC3339用于本地时区)

    let f = ISO8601DateFormatter()
    f.formatOptions = [.withInternetDateTime]
    f.timeZone = TimeZone.current
    let s = f.string(from: Date())
    

    2019-01-09 (标准日期戳,GMT/祖鲁时间)

    let f = ISO8601DateFormatter()
    f.formatOptions = [.withFullDate, .withDashSeparatorInDate]
    let s = f.string(from: Date())
    

    2019-01-08 (当地时区的标准日期戳)

    let f = ISO8601DateFormatter()
    f.formatOptions = [.withFullDate, .withDashSeparatorInDate]
    f.timeZone = TimeZone.current
    let s = f.string(from: Date())
    

    所有四个字符串表示完全相同的时间点。请记住,按字母顺序排序这些字符串也会按时间顺序排序,这使得这个数据数据库不可知(我一直致力于此)。

        8
  •  2
  •   Hani Ibrahim    10 年前

    您必须使用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)
    
        9
  •  1
  •   Awais Fayyaz    6 年前

    斯威夫特4

    获取当前日期和时间

    let currentDate = Date()
    print(currentDate) //this will return current date and time 
    

    但它将是日期类型,以将日期转换为字符串

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy HH:mm" //give the formate according to your need
    let dateStr =  dateFormatter.string(from: currentDate) //which will give the string of current date and time in required dateformate
    
        10
  •  1
  •   Zgpeace    2 年前

    在@lajosdeme上用swift 5来重构答案。我的位置在中国。

    import Foundation
    
    let date = Date() // It is not the local time, less than 8 hours
    print(date)  // 2022-08-05 08:04:20 +0000
    
    extension Date {
        static func localDate() -> Date {
            let nowUTC = Date()
            let timeZoneOffset = Double(TimeZone.current.secondsFromGMT(for: nowUTC))
            guard let localDate = Calendar.current.date(byAdding: .second, value: Int(timeZoneOffset), to: nowUTC) else {
                return nowUTC
            }
            return localDate
        }
    }
    // It is the local time
    print(Date.localDate()) // 2022-08-05 16:04:20 +0000
    
        11
  •  0
  •   David.Chu.ca    3 年前

    我对 Swift Date 是吗 Date 是没有任何日历或时区信息的时间点。我想现在是格林威治时间。如果要显示指定时区中的日期,必须使用 DateFormat API将日期格式化为字符串。

    我有一个iOS应用程序 TapToCount-3W 以记录日期和GPS位置信息。当我旅行时,我用它记录/点击带有日期和GPS的笔记。这些日期是我在旅行国家的当地日期。然而,我发现的问题是,当我回家时,显示的旅行日期是我的祖国日期,而不是旅行国家时区。

    我现在正在使用我的应用程序进行更新。解决方案是在点击时添加时区信息。使用日期和时区信息,本地化日期将正确显示。

    本QA中建议的延长日期的方法实际上是从 Date() 从GMT时间的秒偏移。这是GMT时间,日期与 日期() .

    以下代码来自我的更新(我还包括了@lajosdeme方法作为比较):

    extension Date {
      private func getLocalByID(_ identifier: String?) -> Locale
      {
        let local: Locale
        if let id = identifier, !id.isEmpty {
          local = Locale(identifier: id)
        } else {
          local = Locale.current
        }
        return local
      }
    
      func localizedString(
        timezone: String?,
        dateStyle: DateFormatter.Style = .short,
        timeStyle: DateFormatter.Style = .long
      ) -> String
      {
        let dtFormater = DateFormatter()
        let tz: String = timezone ?? ""
        dtFormater.locale = getLocalByID(tz)
        dtFormater.dateStyle = dateStyle
        dtFormater.timeStyle = timeStyle
        if let timeZone = TimeZone(identifier: tz) {
          dtFormater.timeZone = timeZone
        }
        return dtFormater.string(from: self)
      }
    
      func dateForTimezone(_ timezone: String?) -> Date {
        let nowUTC = Date()
        let tz: TimeZone
        if let timezone = timezone, 
          let v = TimeZone(identifier: timezone)
        {
          tz = v
        } else {
          tz = TimeZone.current
        }
        let timeZoneOffset = 
          Double(tz.secondsFromGMT(for: nowUTC))
        if let dt = 
          Calendar.current.date(byAdding: .second, value: Int(timeZoneOffset), to: nowUTC) 
        {
          return dt
        }
        else {
          return Date()
        }
      }
    }
    
    // Test above extension in Playground
    // [SwiftFiddle][3]
    let dt1 = Date()
    let tz = "America/Edmonton"
    let dt2 = dt1.description(with: .current)
    let dt3 = dt1.localizedString(timezone: tz)
    let dt4 = dt1.dateForTimezone(tz)
    print("Timezone: \(tz)\nDate: \(dt1)\ndescription: \(dt2)\nlocalized string: \(dt3)\ndateForTimezone: \(dt4)")
    

    以下是测试结果 SwiftFiddle playground :

    Timezone: America/Edmonton
    Date: 2022-06-03 15:41:23 +0000
    description: Friday, June 3, 2022 at 3:41:23 PM Coordinated Universal Time
    localized string: 6/3/22, 9:41:23 AM GMT-6
    dateForTimezone: 2022-06-03 09:41:23 +0000