0

In my example I am trying to save the log to measure dates between today and tomorrow.

So, I take users date to save it as old date. My approach is:

1)Save oldDate as Date() 2)Convert and add timezone to out as String 3)Try to convert back to Date, so I can record date with UTC time.

In 3rd step, my UTC hour lost its time and I see UTC 0 time.

Screenshot of the code and output are below:

Code Output

Ege Sucu
  • 160
  • 1
  • 12

1 Answers1

1

Nothing is lost in the process, everything is there. It's just you're understanding the print(date) is not printing according to you, whereas if you print a date object it'll print the date in UTC format

See below example

let oldDate = Date()
let dateFormat = DateFormatter()
dateFormat.dateFormat = "dd/MM/yy HH:mm"
dateFormat.calendar = Calendar.current
let oldDateFormattedString = dateFormat.string(from: oldDate)
print("Old date string: \(oldDateFormattedString)")
print("Old date: \(oldDate)")


let anotherDateFormat = DateFormatter()
anotherDateFormat.dateFormat = "dd/MM/yy HH:mm"
anotherDateFormat.calendar = Calendar.current
let anotherDate = anotherDateFormat.date(from: oldDateFormattedString)

print("Ano date: \(anotherDate!)")

Console

Old date string: 30/11/17 16:35
Old date: 2017-11-30 11:05:47 +0000
Ano date: 2017-11-30 11:05:00 +0000

You can see when you print oldDate and anotherDate the o/p is almost same except for seconds which you didn't include in the date format string.

e.g. add these two lines at the end of the code

let anotherDateString = anotherDateFormat.string(from: anotherDate!)
print("Ano date string: \(anotherDateString)")

You will see your console as

Old date string: 30/11/17 16:41
Old date: 2017-11-30 11:11:51 +0000
Ano date: 2017-11-30 11:11:00 +0000
Ano date string: 30/11/17 16:41

Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184