你如何创建一个 Swift Date 对象? [英] How do you create a Swift Date object?

查看:25
本文介绍了你如何创建一个 Swift Date 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 swift xcode 中根据日期创建日期对象.

How do you create a date object from a date in swift xcode.

例如在 javascript 中你会这样做:var day = new Date('2014-05-20');

eg in javascript you would do: var day = new Date('2014-05-20');

推荐答案

Swift 有自己的 Date 类型.无需使用 NSDate.

Swift has its own Date type. No need to use NSDate.

在 Swift 中,日期和时间存储在 64 位浮点数中,用于测量自 2001 年 1 月 1 日参考日期 00:00:00 UTC.这在 Date 结构 中表示.以下将为您提供当前日期和时间:

In Swift, dates and times are stored in a 64-bit floating point number measuring the number of seconds since the reference date of January 1, 2001 at 00:00:00 UTC. This is expressed in the Date structure. The following would give you the current date and time:

let currentDateTime = Date()

要创建其他日期时间,您可以使用以下方法之一.

For creating other date-times, you can use one of the following methods.

方法一

如果您知道 2001 年参考日期之前或之后的秒数,则可以使用它.

If you know the number of seconds before or after the 2001 reference date, you can use that.

let someDateTime = Date(timeIntervalSinceReferenceDate: -123456789.0) // Feb 2, 1997, 10:26 AM

方法二

当然,使用诸如年、月、日和小时(而不是相对秒)之类的东西来制作 Date 会更容易.为此,您可以使用 DateComponents 指定组件,然后使用 Calendar 创建日期.Calendar 给出了 Date 上下文.否则,它怎么知道用什么时区或日历来表达它?

Of course, it would be easier to use things like years, months, days and hours (rather than relative seconds) to make a Date. For this you can use DateComponents to specify the components and then Calendar to create the date. The Calendar gives the Date context. Otherwise, how would it know what time zone or calendar to express it in?

// Specify date components
var dateComponents = DateComponents()
dateComponents.year = 1980
dateComponents.month = 7
dateComponents.day = 11
dateComponents.timeZone = TimeZone(abbreviation: "JST") // Japan Standard Time
dateComponents.hour = 8
dateComponents.minute = 34

// Create date from components
let userCalendar = Calendar(identifier: .gregorian) // since the components above (like year 1980) are for Gregorian
let someDateTime = userCalendar.date(from: dateComponents)

其他时区缩写可以在此处找到.如果您将其留空,则默认使用用户的时区.

Other time zone abbreviations can be found here. If you leave that blank, then the default is to use the user's time zone.

方法三

最简洁的方法(但不一定是最好的)可能是使用 DateFormatter.

The most succinct way (but not necessarily the best) could be to use DateFormatter.

let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm"
let someDateTime = formatter.date(from: "2016/10/08 22:31")

Unicode 技术标准显示了其他格式DateFormatter 支持.

有关如何以可读格式显示日期和时间的信息,请参阅我的完整答案.还可以阅读这些优秀的文章:

See my full answer for how to display the date and time in a readable format. Also read these excellent articles:

这篇关于你如何创建一个 Swift Date 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆