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

查看:123
本文介绍了如何创建一个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 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.

方法1

如果您知道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

方法2

当然,使用年,月,日和小时(而不是相对秒)之类的东西来制作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.current // user calendar
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.

方法3

最简洁的方式(但不一定是最好的方式)可以是使用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技术标准显示了 >支持.

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

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

  • How to work with dates and times in Swift 3, part 1: Dates, Calendars, and DateComponents
  • How to work with dates and times in Swift 3, part 2: DateFormatter
  • How to work with dates and times in Swift 3, part 3: Date arithmetic

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

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