Localized date from string returns nil [duplicate] - swift

Here is the code excerpt:
func mapping(map: Map) {
time <- (map["time"], TransformOf<Date, String>(fromJSON: {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
//dateFormatter.timeZone = TimeZone(abbreviation: "EEST")
if let argument = $0 {
let date = dateFormatter.date(from: argument)
return dateFormatter.date(from: argument)
}
return nil
}}
$0 is string with "22:12:00". I put "let date" to see what it returns and it's nil. I've looked up for format codes here: http://waracle.net/iphone-nsdateformatter-date-formatting-table/
Code should work actually. What am I doing wrong?
EDIT: Added the whole function
EDIT2: I just noticed it's working properly on iPhone 7 iOS 10.1 simulator but returns nil on my iPod 10.1.1 (2016). This is so weird.

From Technical Q&A QA1480 – NSDateFormatter and Internet Dates (emphasis added):
On the other hand, if you're working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is "en_US_POSIX", a locale that's specifically designed to yield US English results regardless of both user and system preferences.
This will prevent the date from being interpreted according to
the user's regional settings:
let dateFormatter = DateFormatter()
// Set the locale first ...
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
// ... and then the date format:
dateFormatter.dateFormat = "HH:mm:ss"
// ...
See also What is the best way to deal with the NSDateFormatter locale "feechur"?.

Related

Convert String to Date object returns nil [duplicate]

This question already has answers here:
Instantiated optional variable shows as nil in Xcode debugger
(2 answers)
Closed 1 year ago.
I'm having an issue where an attempt to turn a string into a date via a DateFromatter has produced nothing but 'nil' and I don't know where I'm going wrong. The code is as simple as can be:
let testDate = "2021"
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy"
formatter.timeZone = TimeZone(secondsFromGMT: 0)
let date = formatter.date(from: testDate)
Note that this is much simpler than originally, the date I'm trying to format is actually:
"2021-05-01T01:00:00Z"
But I've stripped it right down to narrow down where the issue is.
As you can see from above, I've stripped down to a year, configured the DateFormatter with en_US_POSIX and used only the 'yyyy' as a format. This works in Playgrounds, but it doesn't work in my Xcode simulator (Which is in the US locale) or my own physical iPhone (set to UK locale). That being said, I've no idea why the locale would matter because the string in question is just a year - it'm not even getting a wrong year, just nil.
I'm not sure where I'm going wrong.
Xcode Debugger has a bug as you can see in this post that it will show optional dates as nil even when parsing the date succeeds. If you print the optional date you will see the resulting date.
please use correct format like this for date string:
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
instead of :
formatter.dateFormat = "yyyy"
each date string with specific formate like below code:
let testDate = "2021"
formatter.dateFormat = "yyyy"
or
let testDate = "2021-05-01T01:00:00Z"
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
for more detail please see this link: https://stackoverflow.com/a/52297497/5140621

Date formatter date function returns nil when locale is set to German [duplicate]

Here is the code excerpt:
func mapping(map: Map) {
time <- (map["time"], TransformOf<Date, String>(fromJSON: {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
//dateFormatter.timeZone = TimeZone(abbreviation: "EEST")
if let argument = $0 {
let date = dateFormatter.date(from: argument)
return dateFormatter.date(from: argument)
}
return nil
}}
$0 is string with "22:12:00". I put "let date" to see what it returns and it's nil. I've looked up for format codes here: http://waracle.net/iphone-nsdateformatter-date-formatting-table/
Code should work actually. What am I doing wrong?
EDIT: Added the whole function
EDIT2: I just noticed it's working properly on iPhone 7 iOS 10.1 simulator but returns nil on my iPod 10.1.1 (2016). This is so weird.
From Technical Q&A QA1480 – NSDateFormatter and Internet Dates (emphasis added):
On the other hand, if you're working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is "en_US_POSIX", a locale that's specifically designed to yield US English results regardless of both user and system preferences.
This will prevent the date from being interpreted according to
the user's regional settings:
let dateFormatter = DateFormatter()
// Set the locale first ...
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
// ... and then the date format:
dateFormatter.dateFormat = "HH:mm:ss"
// ...
See also What is the best way to deal with the NSDateFormatter locale "feechur"?.

Date function returning incorrect result

I cannot find an equivalent answer that resolves for me eg
Please see the code. I'm formatting an incoming string (item[9]) downloaded from a webservice.
var cal_end_date: Date!
var dateFormatter = DateFormatter()
let tempEndDate = item[9]
print("item[9]", item[9]) // 20190331
print("tempEndDate", tempEndDate) //20190331
dateFormatter.dateFormat = "YYYYMMDD"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone.autoupdatingCurrent
cal_end_date = dateFormatter.date(from:tempEndDate)!
print(#function, "cal_end_date:", cal_end_date!) //2019-01-31 05:00:00 +0000
The end date has the wrong month! I have confirmed this result by running the code in a playground with a fixed date. Am I doing something wrong here? Has something changed in Swift 5?
Thanks
You can always use nsdateformatter.com to check if your dateFormat for your formatter is correct (next to the Examples check Reference which shows you what each letter/letters represent).
In your case, you have to be carefull on dateFormat's case sensitive. Days and years are represented by small letters
dateFormatter.dateFormat = "yyyyMMdd"

Using DateFormatter produces a result which is off by a day

Using DateFormatter produces a result that is off by a day (actually 12 hours). Using the following code consistently produces dates that show as the previous day. I've been getting this in a number of applications for a while but just finally got around to digging into it.
extension Date
{
func display() -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, yyyy"
print(dateFormatter.locale)
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
let txt = dateFormatter.string(from: self)
print(txt)
return txt
}
}
Other questions that were in this vein suggested changing the locale, thus the added code for that, but I checked the locale and the actual date. If I add 8 hours to the date, I get the correct display result, but adding less than that does nothing. Some dates are being retrieved from the birthday field in the Contacts app, which yields dates that have a time of day 00:00:00 UTC. It would seem that I need to convert the date to local time? The timezone on the device is set to the local timezone (Pacific). That wouldn't seem so bad, but dates retrieved from a date picker aren't in UTC time, they're in local time. I haven't been able to figure out how to tell which timezone the date is in since using the calendar class and trying to extract the .timezone component says that "NSCalendarUnitTimeZone cannot be gotten by this method". Any suggestions on how to create a universal date formatter that works in all cases?
A couple of observations:
If your Date object is in UTC time zone, then set your formatter’s timeZone to TimeZone(secondsFromGMT: 0), too.
If you’re showing the string representation of a Date object in the UI, you do not want to use a locale of en_US_POSIX. You want to show it in the default locate of the device (i.e., don’t change the formatter’s locale at all). You only use en_US_POSIX when dealing with ISO 8601 and RFC 3339 date strings that are used internally or, for example, for exchanging date strings with a web service).
Finally, I would not specify a dateFormat string because not all users expect dates in MMMM dd, yyyy format. For example, UK users expect it in d MMMM yyyy format. When presenting dates in the UI, specify a dateStyle instead. Or, if none of those styles work, go ahead and specify dateFormat, but set it using setLocalizedDateFormatFromTemplate(_:) rather than a fixed string.
Thus, for your purpose, you would do:
extension Date {
var dateString: String {
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeZone = TimeZone(secondsFromGMT: 0)
return formatter.string(from: self)
}
}
Or, if you're calling this a lot, you may want to reuse the formatter:
extension Date {
private static let formatterForDateString: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeZone = TimeZone(secondsFromGMT: 0)
return formatter
}()
var dateString: String {
return Date.formatterForDateString.string(from: self)
}
}
Use the timeZone property, to get the exact date, as shown as below:
formatter.timeZone = TimeZone(secondsFromGMT: 0)
it will solve your purpose!

swift 3 can not convert string to date [duplicate]

Here is the code excerpt:
func mapping(map: Map) {
time <- (map["time"], TransformOf<Date, String>(fromJSON: {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
//dateFormatter.timeZone = TimeZone(abbreviation: "EEST")
if let argument = $0 {
let date = dateFormatter.date(from: argument)
return dateFormatter.date(from: argument)
}
return nil
}}
$0 is string with "22:12:00". I put "let date" to see what it returns and it's nil. I've looked up for format codes here: http://waracle.net/iphone-nsdateformatter-date-formatting-table/
Code should work actually. What am I doing wrong?
EDIT: Added the whole function
EDIT2: I just noticed it's working properly on iPhone 7 iOS 10.1 simulator but returns nil on my iPod 10.1.1 (2016). This is so weird.
From Technical Q&A QA1480 – NSDateFormatter and Internet Dates (emphasis added):
On the other hand, if you're working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is "en_US_POSIX", a locale that's specifically designed to yield US English results regardless of both user and system preferences.
This will prevent the date from being interpreted according to
the user's regional settings:
let dateFormatter = DateFormatter()
// Set the locale first ...
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
// ... and then the date format:
dateFormatter.dateFormat = "HH:mm:ss"
// ...
See also What is the best way to deal with the NSDateFormatter locale "feechur"?.