0

I am playing around with DateFormatter in xcode playground to try to learn the basic of how the date object works in swift.

The following code gave my strange results when i tried to print the result from a string to date conversion from this string "050478" (5. April 1978) to a date . In Norway our social security number starts with ddMMyy, so it is that number i want to convert to a date.

import UIKit

let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "dd/MM/yy"

let myDateString = "05/04/78"

if let myDate = dateFormatterGet.date(from: myDateString)
{
    print(myDate)
}

As you can see, the print(myDate) command gives me the wrong date from the day before what i a gave as argument to the dateformatter (1978-04-04)

Screenshot of xcode playground

BluE_MoOn
  • 103
  • 10
  • 2
    See `dateFormatterGet.date(from: myDateString)!; dateFormatterGet.date(from: myDateString)!.description; print(dateFormatterGet.date(from: myDateString))` instead. It's not a wrong date, it's the same one, just that there is a timezone unseen. – Larme Dec 22 '20 at 14:26

1 Answers1

1

The local time zone in Norway on May 5th at 0:00 is UTC+0100.

However print() displays dates always in UTC(+0000) which is May 4th at 23:00.

Replace

print(myDate) 

with

print(myDate.description(with: .current))

to get the local date and time

vadian
  • 274,689
  • 30
  • 353
  • 361