Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/112.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 日期组件给出了错误的日期_Ios_Swift3_Nsdatecomponents - Fatal编程技术网

Ios 日期组件给出了错误的日期

Ios 日期组件给出了错误的日期,ios,swift3,nsdatecomponents,Ios,Swift3,Nsdatecomponents,我正在尝试使用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

我正在尝试使用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)!

调试时,我发现在声明todayDate之后,它的值是
2016-11-11 07:44:44+0000
。使用dateComponents后,值更改为
2016-11-10 18:30:00+0000
。然而,根据我的位置,这一天应该是11月11日,时间应该在下午1点或2点之间。为什么会发生这种情况?

您没有在组件中指定时区,也没有指定小时分秒。所以,所有这些值都假设为零。结果时间为您指定的年份、月份和日期的格林威治标准时间午夜

打印结果时,您指定了当前时区,该时区与当前时区相差5小时30米


我猜你在印度。

我在上面指定了
dateComponents.timeZone=timeZone.current
。让我也尝试添加小时和分钟,然后再试一次。添加.hour和.minute之后,日期是正确的,但时间仍然是UTC。您还需要提取时区。不要单独设置。