0

I've formated a string back to date which basic conversion and I've got totally different date.

import UIKit

extension String {
    func toDate(dateFormat: String) -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = dateFormat
        return dateFormatter.date(from: self)!
    }
}

let date = "01/24/2018 09:59:24"

print(date.toDate(dateFormat: "MM/dd/YYYY hh:mm:ss"))

enter image description here

Why it has decremented for about one month and one hour ?

EDIT

import UIKit

extension String {
    func toDate(dateFormat: String) -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = dateFormat
        dateFormatter.timeZone = TimeZone.current
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        return dateFormatter.date(from: self)!
    }
}

extension Date {
    func toString(_ format: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        dateFormatter.timeZone = TimeZone.current
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        return dateFormatter.string(from: self)
    }
}
let date = Date().toString("MM/dd/yyyy hh:mm:ss")
print(date)
print(date.toDate(dateFormat: "MM/dd/yyyy hh:mm:ss"))

RESULT

01/24/2018 12:48:33
2018-01-23 23:48:33 +0000
noname
  • 127
  • 1
  • 9
  • 1
    add the code instead of image. – adarshaU Jan 24 '18 at 11:39
  • 1
    Three things. Firstly, you are using `YYYY` instead of `yyyy` (see details [here](https://stackoverflow.com/q/15133549/3151675)). Secondly, you are not using `en_US_POSIX` as the locale, that can lead to incorrect/invalid results. Thirdly, printed dates use UTC instead of the time zone of the locale. – Tamás Sengel Jan 24 '18 at 11:39
  • @the4kman Got ya'. I've added a `locale` as `en_US_POSIX` and then `timeZone`. Thank you ! – noname Jan 24 '18 at 11:43
  • @the4kman Could you have a look at the edit section ? I've done those changes and the dates are different. – noname Jan 24 '18 at 11:50
  • 1
    ... and for 24 hour mode you have to use `HH` – vadian Jan 24 '18 at 11:56
  • @vadian Thank you, good point. Still I am getting -1h. Probably it's becouse of the time zone, but in both cases I've used current time zone. – noname Jan 24 '18 at 11:59
  • Actually the answer is quite simple: If the conversions do not work as expected then (in 99% of all cases) your date format is wrong, and it is time to study http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns and https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html – Martin R Jan 24 '18 at 12:00
  • The date formatter considers the local time zone while `print` displays the `Date` in UTC – vadian Jan 24 '18 at 12:01
  • 1
    @noname: With respect to "-1h", see https://stackoverflow.com/questions/39937019/nsdate-or-date-shows-the-wrong-time. – Martin R Jan 24 '18 at 12:03

1 Answers1

1

Set the locale and timezone to avoid invalid results. The return value of the extension should be Date? since the string may not be a valid date. And since dateFormat is not optional, it should be a valid date format, see here for more details.

import UIKit

extension String {
    func toDate(dateFormat: String, locale : Locale? = nil, timezone: TimeZone? = nil) -> Date? { //locale and timezone are optional with a default nil value
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = dateFormat 
        dateFormatter.locale = locale
        dateFormatter.timeZone = timezone
        return dateFormatter.date(from: self)
    }
}

You can use it like so:

let string = "01/24/2018 09:59:24"
let myLocale = Locale(identifier: "en_US_POSIX")
let myTimeZone = TimeZone(abbreviation: "PCT")

print(string.toDate(dateFormat: "MM/dd/yyyy HH:mm:ss",
      locale: myLocale,
      timezone: myTimeZone))
ielyamani
  • 17,807
  • 10
  • 55
  • 90
  • How does this solve the problem? You use the same date format as in the question, where "YYYY" and "hh" are both wrong, as addressed in above comments. And (apart from the fact that the question was already closed as a duplicate), some *explanations* would be more helpful than a pure code dump. – Martin R Jan 24 '18 at 12:21
  • @MartinR edited the answer, dateFormat is a user input here, and error handling should take place if necessary. – ielyamani Jan 24 '18 at 12:26