0

I want to extract .hour from a Date variable.
There is a Event1 class which has startDate property.
allEvent is an array of Event1.

var startDate: Date?
...
var allEvent: [Event1] = [Event1]()
...
if let validDate = allEvents[4].startDate {
   print(validDate) 
   let hour = Calendar.current.component(.hour, from: validDate)
   print(hour) 
}

output

2017-07-05 12:57:22 +0000   // validDate
17                          // hour

output should not be 17. It should have been 12.

Fattaneh Talebi
  • 727
  • 1
  • 16
  • 42
  • 1
    There is no error. "2017-07-05 12:57:22 +0000" is the output in the GMT timezone, and `17` is the hour in your local timezone. – Martin R Jul 08 '17 at 11:02
  • @MartinR When I write "validDate = Date()" the output is correct but the type of validDate is the same. – Fattaneh Talebi Jul 08 '17 at 11:06
  • 1
    A Date is an absolute point in time, and `print(someDate)` prints the time using GMT. On the other hand, `Calendar.current.component` computes the components according to your local timezone. Assuming that you are in the Teheran timezone: "2017-07-05 12:57:22 +0000" is the same point in time as "2017-07-05 17:27:22 +0430". There is no error. – Martin R Jul 08 '17 at 11:13
  • 1
    See also: https://stackoverflow.com/questions/8466744/getting-date-from-nsdate-date-off-by-a-few-hours, https://stackoverflow.com/questions/6229024/nsdate-format-outputting-wrong-date or https://stackoverflow.com/questions/39937019/nsdate-or-date-shows-the-wrong-time. – Martin R Jul 08 '17 at 11:17
  • @MartinR Sure. Thanks. – Fattaneh Talebi Jul 08 '17 at 11:19

0 Answers0