iOS DateFormatter giving nil ,When device Timezone and region changes [duplicate] - ios

This question already has answers here:
What is the best way to deal with the NSDateFormatter locale "feature"?
(4 answers)
DateFormatter doesn't return date for "HH:mm:ss"
(1 answer)
Swift: NSDateFormatter dateFromString returns nil on devices
(1 answer)
Closed 4 years ago.
I have a date in string like this
let time = "Wed Oct 10 12:22:32 UTC 2018"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EE MM dd HH:mm:ss zz yyyy"
let rawDate = dateFormatter.date(from: time) // GETTING rawDate
dateFormatter.dateFormat = "d MMM yyyy, h:mm a"
guard let date = rawDate else { return "" } // rawDate NIL HERE
let time = dateFormatter.string(from: date)
It works fine in my timezone Mumbai and region India. But when i'm changing it to some other region and timezone, rawDate is getting nil.
What's wrong i'm doing?
P.S: Please give a generic answer, No fixed timezone or Locale is needed.
Update: As the duplicate reference consist en_US posfix, This doesn't make code generic, if I use en_GB or something else the data will be incorrect.

Related

Swift: Converting string to date [duplicate]

This question already has answers here:
How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?
(13 answers)
Closed 5 months ago.
I have a date as String but I want to convert it to Date.
The date in string looks like this - "2022-09-09T07:00:00.0000000".
Code to convert it to Date:
public static func dateStringToDate(dateString: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.autoupdatingCurrent
dateFormatter.timeZone = TimeZone.current
dateFormatter.setLocalizedDateFormatFromTemplate("MM-dd-yyyy HH:mm:ss")
return dateFormatter.date(from: dateString)
}
No matter what I do, I keep getting nil as the output. I tried with ISO8601 template as well and got nil. I commented out line "setLocalizedDateFormatFromTemplate" but still got nil. Can't figure out what am I missing or doing wrong in the code.
First of all, this is an excellent resource. I think what you are looking for is this:
func dateStringToDate(dateString: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS"
return dateFormatter.date(from: dateString)
}
dateStringToDate(dateString: "2022-09-09T07:00:00.0000000")
Sep 9, 2022 at 7:00 AM
You have the year, then month, then day, then hour, minute, second, fractional seconds
Use this Snippet of code
func dateStringToDate(dateString: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.autoupdatingCurrent
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
return dateFormatter.date(from: dateString)
}
You were not providing the proper date format

How do I convert this, "2021-07-05T22:26:51.159Z" to Date() with swift [duplicate]

This question already has an answer here:
Swift ISO8601 format to Date returning fatal error
(1 answer)
Closed 1 year ago.
I think this is an ISO8601 formatted timestamp.
2021-07-05T22:26:51.159Z
I'm trying to convert it with ISO8601DateFormatter() in swift 5.
Here's what I've tried:
let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = .withFullDate
//ISO8601DateFormatter().formatOptions = .withFractionalSeconds
let d = "2021-07-05T22:26:51.159Z"
let date = dateFormatter.date(from: d)
The result:
date = 2021-07-05 00:00:00 UTC
The day is correct, the time is not. I've tried to set the .withFractionalSeconds option. Didn't help.
How should I convert this format?
You can use standard date formatter to achieve this:
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
let date = dateFormatter.date(from: d)
print(date)

DateFormatter with AM/PM returns nil [duplicate]

This question already has answers here:
Convert String to URL (Why is resulting variable nil)
(1 answer)
Instantiated optional variable shows as nil in Xcode debugger
(2 answers)
Closed 3 years ago.
I know that this topic is fully discussed here and in other forums.
Unfortunately, I still cannot understand why the Date is nil.
Note that when I run the code in the Debugger or in Playground then it works totally fine.
It's something to do with the fact that it runs on the device.
var dateString = "2019-12-17 3:48:02 PM"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.current
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss a"
let date = dateFormatter.date(from: dateString) // date is nil
Add en_US as your Locale, like this:
dateFormatter.locale = NSLocale(localeIdentifier: "en_US")

DateFormatter returns wrong time [duplicate]

This question already has answers here:
Getting date from [NSDate date] off by a few hours
(3 answers)
Closed 5 years ago.
I did an extension for Date that returns a formatted string:
extension Date {
var myFormattedDate : String {
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "EEEE, MMMM d, y (HH:mm a)"
return formatter.string(for: self)!
}
}
On runtime, I set a breakpoint inside the myFormattedDate property.
po self printed:
2017-09-05 08:50:00 +0000
po formatter.string(for: self)! printed:
Tuesday, September 5, 2017 (11:50 AM)"
What could be the problem?
Thanks!
Printing a Date always returns an UTC time, regardless of the local time zone. Just avoid printing a Date object directly if you want to see the date with the proper time zone in your console.

How to convert milliseconds to date string in swift 3 [duplicate]

This question already has answers here:
NSDate timeIntervalSince1970 not working in Swift? [duplicate]
(3 answers)
Closed 6 years ago.
I am trying to convert milliseconds to date string in swift 3,i tried by setting date fomatter but i am not getting current date string.
var milliseconds=1477593000000
let date = NSDate(timeIntervalSince1970: TimeInterval(milliseconds))
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
formatter.locale = NSLocale(localeIdentifier: "en_US") as Locale!
print(formatter.string(from: date as Date))
output:
22-01-48793 01:30:00
Try this,
var date = Date(timeIntervalSince1970: (1477593000000 / 1000.0))
print("date - \(date)")
You will get output as date :
date - 2016-10-27 18:30:00 +0000
How about trying this -
let milisecond = 1479714427
let dateVar = Date.init(timeIntervalSinceNow: TimeInterval(milisecond)/1000)
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy hh:mm"
print(dateFormatter.string(from: dateVar))
Have a look at the documentation of NSDate:
convenience init(timeIntervalSince1970 secs: TimeInterval)
Returns an NSDate object initialized relative to the current date and time by a given number of seconds.
Just convert your milliseconds to seconds and you should get the correct date.

Resources