Reputation: 11
Here is the thing. I have my iPhone in am/pm format and iPhone Language in Spanish(MX). when I ask for the date, I get something like 2018-03-21 5:14:59 a. m. +0000 and it's a date type, then I try to convert it to string in 24hours format, and I get something like 2018-03-20 23:14:59 and it's a String type, BUT when I try to convert that string into date, I get the same date in am/pm format again 2018-03-21 5:14:59 a. m. +0000 I don't know what else to do, all I want is convert my am/pm date to 24hours date NOT STRING. Help me please. Here is my code in Swift 4
let todayDate = Date()
print("todayDate: \(todayDate)")
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ss"
let stringDate = dateFormatter.string(from: todayDate)
print("stringDate: \(stringDate)")
let dateFromString = dateFormatter.date(from: stringDate)
print("dateFromString: \(dateFromString!)\n\n\n")
this is my console results
todayDate: 2018-03-21 5:14:59 a. m. +0000
stringDate: 2018-03-20 23:14:59
dateFromString: 2018-03-21 5:14:59 a. m. +0000
Upvotes: 0
Views: 1555
Reputation: 347214
all I want is convert my am/pm date to 24hours date NOT STRING
That's not how Date
works.
Date values represent a time interval relative to an absolute reference date.
Date
is simply a container for the period of time since the reference date, it does not carry any kind of formatting information itself.
let dateFromString = dateFormatter.date(from: stringDate)
print("dateFromString: \(dateFromString!)\n\n\n")
is simply converting the stringDate
(2018-03-20 23:14:59
in your example) back to Date
object and print
is using the Date
s description
implementation to provide you with information about it's current value
So, if we instead added...
print("dateFromString: \(dateFormatter.string(from: dateFromString!))\n\n\n")
It would print 2018-03-21 16:44:17
Your best bet is not to care. Simply carry the value around in a Date
object and format it to String
when you need to display it to the user or otherwise need it formatted - that's the point of having formatters
Upvotes: 4