简体   繁体   English

DateComponents提供错误的日期

[英]DateComponents giving wrong date

I am trying to convert today's date using DateComponents: 我想使用DateComponents转换今天的日期:

let calendar = Calendar.current        
//add today's date
var todayDate = Date()
var dateComponents = calendar.dateComponents([.day, .month, .year], from: todayDate)
dateComponents.timeZone = TimeZone.current
todayDate = calendar.date(from: dateComponents)!

While debugging I found that after declaring todayDate, its value was 2016-11-11 07:44:44 +0000 . 调试时我发现在今天宣布日期后,它的价值是2016-11-11 07:44:44 +0000 After using dateComponents, the value changed to 2016-11-10 18:30:00 +0000 . 使用dateComponents后,值更改为2016-11-10 18:30:00 +0000 Whereas according to my location, the day should be 11th November, and the time should be somewhere between 1 or 2 PM. 根据我的位置,那天应该是11月11日,时间应该是在下午1点或2点之间。 Why is this happening? 为什么会这样?

You haven't specified a timezone, nor hours minutes and seconds in your components. 您尚未指定组件中的时区,小时数和小时数。 So, all these values are assumed to be zero. 因此,假设所有这些值都为零。 The resulting time is at midnight GMT on the year, month and day that you specified. 生成的时间是您指定的年,月和日的格林威治标准时间午夜。

When you printed the result, you specified your current timezone, which appears to be 5h 30m different. 打印结果时,您指定了当前时区,该时区似乎是5小时30米不同。

I'm guessing you are in India. 我猜你在印度。

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

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