ios Swift - 获取本地日期和时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28404154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:45:07  来源:igfitidea点击:

Swift - Get local date and time

iosswiftnsdate

提问by Mohammad Nurdin

How can I get local date and time in Swift?

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

let last_login = String(NSDate.date())

采纳答案by Mohammad Nurdin

I already found the answer.

我已经找到了答案。

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
let dateInFormat = dateFormatter.stringFromDate(NSDate())

回答by Leo Dabus

update: Xcode 8.2.1 ? Swift 3.0.2

更新:Xcode 8.2.1?斯威夫特 3.0.2

You can also use the Date method description(with locale: Locale?)to get user's localized time description:

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

A string representation of the Date, using the given locale, or if the locale argument is nil, in the international format YYYY-MM-DD HH:MM:SS ±HHMM, where ±HHMM represents the time zone offset in hours and minutes from UTC (for example, “2001-03-24 10:45:32 +0600”).

日期的字符串表示形式,使用给定的语言环境,或者如果语言环境参数为零,则采用国际格式 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"

The method above it is not meant to use when displaying date and time to the user. It is for debugging purposes only.

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

When displaying local date and time (current timezone) to the user you should respect the users locale and device settings. The only thing you can control is the date and time style (short, medium, long or full). Fore more info on that you can check this post shortDateTime.

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

If your intent is to create a time stamp UTC for encoding purposes (iso8601) you can check this post iso8601

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

回答by vikingosegundo

use NSDateFormatter, either by setting the format

使用 NSDateFormatter,或者通过设置格式

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

or styles

或样式

dateFormatter.dateStyle = .NoStyle
dateFormatter.timeStyle = .MediumStyle

回答by lajosdeme

In case you want to get a Date objectand not a string representation you can use the following snippet:

如果您想获取Date 对象而不是字符串表示,您可以使用以下代码段:

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
    }
}

Use it like this:

像这样使用它:

let now = Date().localDate()

回答by ScottyBlades

Leo's answer is pretty good. I just wanted to add a way to use it as a computed property.

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

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

Use it like so:

像这样使用它:

print(currentTime)

Or you can encapsulate it:

或者你可以封装它:

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

And then you can use it anywhere you use a string:

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

var time: String = .currentTime

回答by Warif Akhand Rishi

let expiryDate: Date = ...
let localizedDateString = DateFormatter.localizedString(from: expiryDate, dateStyle: .medium, timeStyle: .short)

"10 Sep 2017, 14:37"

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

回答by bsod

To get back the most common string formats (when dealing with queries and databases):

找回最常见的字符串格式(在处理查询和数据库时):

Swift 4

斯威夫特 4

2019-01-09T01:07:04Z(RFC3339 in GMT/Zulu time)

2019-01-09T01:07:04Z(格林威治标准时间/祖鲁时间的RFC3339)

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

2019-01-08T17:04:16-08:00(RFC3339 accounting for local time zone)

2019-01-08T17:04:16-08:00(RFC3339 考虑本地时区)

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

2019-01-09(standard date stamp in GMT/Zulu time)

2019-01-09(格林威治标准时间/祖鲁时间的标准日期戳)

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

2019-01-08(standard date stamp accounting for local time zone)

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

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

All four strings represent the exact same date and time. And don't forget that sorting these strings (in these formats) in alphabetical order puts them in chronological order, which means there is no need to store them as date objects in the database since you can sort and query chronologically using a basic a-to-z sort.

所有四个字符串都表示完全相同的日期和时间。并且不要忘记按字母顺序对这些字符串(以这些格式)进行排序会将它们按时间顺序排列,这意味着无需将它们作为日期对象存储在数据库中,因为您可以使用基本的 a- 按时间顺序排序和查询to-z 排序。

回答by Hani Ibrahim

You have to use NSDateFormatter

你必须使用 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)

回答by Ganesh Manickam

Swift 4

斯威夫特 4

To get current date and time

获取当前日期和时间

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

but that will be in date type to convert date into string

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

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

回答by ninahadi

Swift 5
If you want to do it manually,
Date() will always return current UTC time

Swift 5
如果您想手动执行此操作,
Date() 将始终返回当前 UTC 时间

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

如果你住在马来西亚,让我们说。它是 UTC+8(意味着快 8 小时)
您可以使用 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