Swift date format returning wrong date

4.5k views Asked by At

I need to convert my date to string and then string to date. date is "2020-10-17 1:22:01 PM +0000"

Here is my date to string conversion code:

                    let formatter = DateFormatter()
                    formatter.locale = Locale(identifier: "en_US_POSIX")
                    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
                     let string = formatter.string(from: "2020-10-17 1:22:01 PM +0000")
                    let createdAT = string

its returning "2020-10-17 18:51:30+05:30"

Here is my string to date conversion code:

     let dateFormatter = DateFormatter()
     dateFormatter.locale = Locale(identifier: "en_US_POSIX")
     dateFormatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ssZ"
     let date = dateFormatter.date(from:date)!

its returning "2020-10-17 1:21:30 PM +0000 - timeIntervalSinceReferenceDate : 624633690.0"

its returning the wrong date after i convert string to date. i need "2020-10-17 18:51:30+05:30" this time to be return when i convert string to date.....

1

There are 1 answers

0
JeremyP On BEST ANSWER

The code in your question is muddled up. You try to convert a string into a string in the first example and something unspecified into a Date in the second example.

Here's how to convert a Date into a String:

import Foundation

let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
let string: String = formatter.string(from: Date())

print(string) // prints for example 2020-10-18T10:54:07+01:00

Here's how to convert a string into a date

let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ssZ"
let date: Date = formatter.date(from: "2020-10-18 10:59:56+0100")! // In real life, handle the optional properly
print(date)  // prints 2020-10-18 09:59:56 +0000

When you print a Date directly, it automatically uses UTC as the time zone. This is why it changed it in the code above.

In the examples, I explicitly specified the type of string and date to show what type they are. Type inference means you can omit these in normal code.

As a general rule when handling dates:

  • always use Date in your code. Date is a type that stores the number of seconds since Jan 1st 1970 UTC.
  • Only convert dates to strings when displaying them to the user or communicating with an external system.
  • When calculating periods etc, always use a Calendar to get things like date components and intervals in units other than seconds. You might think to get "the same time tomorrow" you could just add 24 * 60 * 60 to a Date but in many countries, like mine, that will work on only 363 days in the year. Calendar will correctly handle things like daylight saving and leap years.