Convert String To correct date [duplicate] - swift

This question already has answers here:
Getting back a date from a string
(3 answers)
Closed 4 years ago.
I'm working on event application. I'm let the user create the event and save it in DB to remind him. now I'm facing an issue when the user put the date as string and from my code when I'm trying to convert it to date formate it gives me wrong date. for example if the user put in the text "01-03-2018 10:00" after convert it to date it returns to me "2017-12-24 10:00:00 +0000".
here is my code
let startDateFormatter = DateFormatter()
startDateFormatter.dateFormat = "dd-MM-YYYY HH:mm"
startDateFormatter.locale = Locale(identifier: "en_US_POSIX")
startDateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
let d = "01-03-2018 10:00”
let startDate = startDateFormatter.date(from: d)
print(startDate!)
so any idea please

Finally I found it. it regarding to date formatter, when I changed the date formatter form startDateFormatter.dateFormat = "dd-MM-YYYY HH:mm”
to
endDateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
endDateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
` worked with me. I shared the answer if anyone faced the same issue

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

DateFormatter date from string returns nil when iPhone Date & Time 24-Hour Time is off [duplicate]

This question already has an answer here:
DateFormatter doesn't return date for "HH:mm:ss"
(1 answer)
Closed 2 years ago.
I am working on an app that initializes dates from strings returned from the backend. The dateString is returned using the following format: "2020-03-05T09:00:00+00:00"
The method I have to do the conversion is:
extension Date {
static func convertDate(_ dateString: String?) -> Date? {
guard let dateString = dateString else { return nil }
let dateFormatter = DateFormatter()
dateFormatter.setLocalizedDateFormatFromTemplate("yyyy-MM-dd'T'HH:mm:ssZZZZZ")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
return dateFormatter.date(from: dateString)
}
}
Everything was working fine until someone reported that if the user switches off "24-Hour Time" in settings the method above returns nil.
What am I doing wrong?
Thank you
You're using a very standardized timestamp format, which allows you to take advantage of the ISO8601DateFormatter.
let dateString = "2020-03-05T09:00:00+00:00"
let df = ISO8601DateFormatter()
df.formatOptions = [.withInternetDateTime]
if let date = df.date(from: dateString) {
print(date) // 2020-03-05 09:00:00 +0000
}
If a machine (like your server) is generating the timestamp then it will (should) always be in zulu time (GMT) so you don't need to do anything beyond this. You could specify a time zone but there isn't a point since the string will always zero it out for you.
df.timeZone = TimeZone(secondsFromGMT: 0)
This string represents an absolute moment in time. If you need a relative moment in time, such as the local time from the source, you'll need to identify that time zone and apply it here, which is also very straighforward.

Xcode 11, swift. Dateformatter always return nil [duplicate]

This question already has answers here:
Instantiated optional variable shows as nil in Xcode debugger
(2 answers)
Closed 2 years ago.
I have a problem with converting value from String to Date in Swift.
It always returns nil. What am I doing wrong?
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: "2019-05-03")
Here is what is happening in the debugger in Xcode
Update:
It would appear that it is a bug in Xcode. Trying your code in the viewDidLoad and setting a breakpoint causes the lldb description of the date to be nil, however it correctly prints the expected value out.
You can see more about the bug at this SO post, thanks to OOPer for the link.
Currently this bug is still occurring in Xcode 11.2-beta
A couple of points
Use .dateFormat instead of .format
Use the correct quotation marks " instead of ”, also you should remove the space from your date format string.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: "2019-05-03")
It does not have a nil value. Use .dateFormat instead of .format It's a simple as this:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: "2019-05-03")
// Optional(2019-05-02 23:00:00 +0000)

How to properly convert date into NSDate? (Unexpectedly found nil while unwrapping an Optional value) [duplicate]

This question already has an answer here:
DateFormatter doesn't return date for "HH:mm:ss"
(1 answer)
Closed 3 years ago.
I'm pulling in a contest end date from remote config (a string), and trying to cast it as an NSDate to use in a timer.
let contestEndDateFormatter = DateFormatter()
contestEndDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
contestEndDate = contestEndDateFormatter.date(from: contestEndDateFromRemoteConfig)! as NSDate
As you can see in the image, the string "2019-05-29 23:59:59" is definitely in the variable "contestEndDateFromRemoteConfig" (so it's not an issue with remote config); however, I'm obviously doing something wrong because it throws the error "Unexpectedly found nil while unwrapping an Optional value."
I believe the dateFormat is correct and matches the string (which was the suggestion from similar stackoverflow questions), so that shouldn't be the issue either.
Can anybody see why this would be throwing an error?
Thanks in advance for any direction!
Try this:
var date = "2019-05-29 23:59:59"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00")
let formattedDate = dateFormatter.date(from: date)
if let formattedDate = formattedDate {
print(formattedDate)
}

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"