简体   繁体   English

Date()和Calendar.dateComponents的日期不匹配

[英]day for Date() and Calendar.dateComponents don't match up

I'm trying to get the current date to print in a particular format (YYYYMMD) for AWS security credentials and I noticed that when I do Date() , the day is the 4th which is the correct value: 我试图获取当前日期以特定格式(YYYYMMD)进行AWS安全凭证打印,并且我注意到当我执行Date() ,日期是第4天,这是正确的值:

    let date = Date()
    print("\(date)")  //2016-10-04 00:56:28 +0000

Now, I want to print the date in the format I desire so, but I keep getting the day value as the 3rd: 现在,我想以所需的格式打印日期,但我不断将日值作为第三个:

    let calendar = Calendar.current
    let date = Date()
    let components = calendar.dateComponents([.day], from: date)
    print("\(components.day)")  //Optional(3)

S3 is expecting the date to be the 4th. S3预计该日期为4日。 How can I fix this? 我怎样才能解决这个问题?

It's because of time zone difference. 这是因为时区不同。 date will return the UTC time and date but calendar will return the date and time based on your device's time zone. date将返回UTC时间和日期,而calendar将根据设备的时区返回日期和时间。 If you need the day number in UTC just set the time zone of the calendar object to UTC after you create it: 如果您需要UTC中的日期,只需在创建日历对象后将其时区设置为UTC:

let calendar = Calendar.current
calendar.timeZone = TimeZone(abbreviation: "UTC")!

Now it will always match the value that is returned by Date() 现在它将始终与Date()返回的值匹配

When you print a date using 当您使用

 print("\(date)")

You get the date and time in UTC, which is probably not what you want. 您以UTC格式获取日期和时间,这可能不是您想要的。

If you want to display your date in your local time zone, create a date formatter and use that: 如果要在本地时区显示日期,请创建一个日期格式器并使用它:

let dateFormatter = NSdateFormatter()
let dateFormatter.dateStyle = .medium
let dateFormatter.timeStyle = .medium

let dateString = dateFormatter.StringFromDate(date)
print ("date = \(dateString)")

If you do this a lot, you might want to create an extension on NSDate displayString so you can use that to display your dates without having to write additional code. 如果您经常这样做,则可能要在NSDate displayString上创建扩展名,以便可以使用它来显示日期而不必编写其他代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM