How to convert string to date correctly? [duplicate] - ios

This question already has answers here:
NSDateFormatter still parsing instead having incorrect format
(3 answers)
Closed 3 years ago.
Why does dateFormatter return the correct date from an invalid format string?
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: "2020/////07////////10") //"Jul 10, 2020 at 12:00 AM"

I will say more - it also works unexpectedly
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let dotDate = dateFormatter.date(from: "2020....07...10") // Optional(2020-07-09 21:00:00 +0000)
let commaDate = dateFormatter.date(from: "2020,,,,07,,,,10") // Optional(2020-07-09 21:00:00 +0000)
My version is probably the issue in internal implementation on Apple side and comparison with the ASCII code table, where the codes of these characters (,,-,.,/) are in order (from 44 to 47)

This is probably a part of their algorithm.
If you want the formatter to return nil in this case you can change the dateFormat to:
dateFormatter.dateFormat = "yyyy/MM/dd"
Results
let date = dateFormatter.date(from: "2020/////07////////10") // nil
let date2 = dateFormatter.date(from: "2020/07/10") // Jul 10, 2020 at 12:00 AM"
let date3 = dateFormatter.date(from: "2020.07.10") // Jul 10, 2020 at 12:00 AM"

I did run your code and it gives nil
Whereas if I enter correct date format then I receive the output
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: "2020-7-10")
print(date) // Optional(2020-07-10 00:00:00 +0000)

Related

String to date conversion sometimes returns nil with DateFormatter

I just read over this post which details that you need to set a locale before the format before attempting to convert a given string back to a date.
I have the below code that follows that format but the conversion from string to date still seems to return nil though in the playground it seems to work fine.
// originalDate style is the .full style, "Friday, December 10, 2021 at 4:17:04 PM Pacific Standard Time"
let df: DateFormatter = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "MMM d, yyyy" // Sep 12, 2018 format'
let newDate = df.date(from: originalDate)
let newStringDate = df.string(from: newDate!) // throws found nil when unwrapping
What could be causing this?
Edit 1: I'm pulling a string type out of a sqlite db using SQLite.swift
Answer for your question (string to date is nil): While converting from string to date, you have to use the same format as String. I assume the originalDate from your comments. You have to change your code like this
let originalDate = "Friday, December 10, 2021 at 4:17:04 PM"
let df: DateFormatter = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "EEEE, MMMM d, yyyy 'at' h:mm:ss a"
let newDate = df.date(from: originalDate)
print(newDate)
If you again want string from date then you can again specify which format you want.
df.dateFormat = "MMM d, yyyy" // Sep 12, 2018 format'
let newStringDate = df.string(from: newDate!)
print(newStringDate)
Note: If you try to log the newDate value in the console using print, sometimes it shows nil. In that case, you can try 'po newDate' in the console.

DateFormatter returning nil for valid Date in format "dd/MM/yyyy" [duplicate]

I have the below code on playground and app and DateFormatter are returning nil just for the date "1990-10-21":
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd"
let date1 = dateFormatter.date(from: "1990-10-20") // "Oct 20, 1990 at 12:00 AM"
let date2 = dateFormatter.date(from: "1990-10-21") // nil
let date3 = dateFormatter.date(from: "1990-10-22") // "Oct 22, 1990 at 12:00 AM"
Testing with 1989, 2021... works fine...
Does anyone knows why or something about this? is it a bug?
There are three issues with your code. First YYYY is for YearForWeekOfYear. What you need is yyyy. Second you are not passing the time. Note that not all days starts at 12:00am (daylight savings transition dates). You can prevent the date formatter returning nil by setting its calendar or passing a valid time (12pm) along with the date. Third you should always set the locale to "en_US_POSIX" when using a fixed date format:
let dateFormatter = DateFormatter()
dateFormatter.calendar = .current
dateFormatter.locale = .init(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd"
let date1 = dateFormatter.date(from: "1990-10-20") // "Oct 20, 1990 at 12:00 AM"
let date2 = dateFormatter.date(from: "1990-10-21") // "Oct 21, 1990 at 1:00 AM"
let date3 = dateFormatter.date(from: "1990-10-22") // "Oct 22, 1990 at 12:00 AM"

Getting date from DateFormatter without delimiter(/ or -) returns wrong date:

Getting date from DateFormatter without delimiter returns the wrong date,
As per our requirement, we cannot use / or - in our date formatter string.
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.timeZone = TimeZone(identifier: "UTC")
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.calendar = Calendar(identifier: .iso8601)
dateFormatter.dateFormat = "ddMMyyyy"
dateFormatter.date(from: "1112987")
this returns "Nov 1, 2987 at 8:00 AM", however it should be "Dec 11 0987"
Another Example:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMddyyyy"
dateFormatter.date(from: "1131987") // "Jan 13, 1987 at 12:00 AM"
This should return nil as November 31st is a invalid date
Please suggest any solution
You have to update your date format from ddMMyyyy to MMddyyyy.
Your code :-
dateFormatter.dateFormat = "ddMMyyyy"
New code :-
dateFormatter.dateFormat = "MMddyyyy"
Also, you have to set 4 digit year instead of 3 digit.
Your code :-
dateFormatter.date(from: "1112987")
New code :-
dateFormatter.date(from: "11120987"
If you get any issue post your reply.

iOS Swift: how to convert specific date string format to Date object, when string contains time zone abbreviation?

I am getting a date string from server in the format of "March 08, 2018 16:00:00 PST" where there is a lot of whitespace between Month & Date.
My intention is to basically remove those extra whitespaces. My idea is that- I will convert the string into Date object, and then convert back to string.
How can I convert this into Date object using Date Formatter, taking timezone into consideration.
I am concerned about the "PST" here. While converting the Date to String, I will need in the format - "March 08, 2018 16:00:00 PST" i.e. PST (or whatever time zone comes in) should stay intact in the final string.
extension String {
func getDate(fromFormat format: String = "MMMM dd, yyyy HH:mm:ss zzz") -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter.date(from: self)
}
}
let myDateString = "March 08, 2018 16:00:00 PST"
myDateString.getDate()
You can call with other time formats too.
Try this
let isoDate = "March 08, 2018 16:00:00 PST"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, yyyy HH:mm:ss z"
let date = dateFormatter.date(from: isoDate)!
Try this
class func stringToDate (dateString:String, dateFormat:String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
let dateFromString = dateFormatter.date(from: dateString)
return dateFromString
}

How to extract day, month and year (dd-MM-yyyy) from Date (2018-09-28 09:42:00 +0000 ) without time in Date format - iOS swift?

I want to get 2018-09-28 from 2018-09-28 09:42:00 +0000 in Date format. I
can extract the same in string format but I want to get this in Date format. Here is my sample code.
let date = Date(timeIntervalSince1970: (TimeInterval(timer/1000)))
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd"
let myDate = df.string(from: date)
let updateDate = df.date(from: myDate)
//date - 2018-09-28
//updateDate - 2018-09-28 09:42:00 +0000
You can simply get your date string prefix 11 and insert noon time when parsing your string:
let str = "2018-09-28 09:42:00 +0000"
let df = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "yyyy-MM-dd HH:mm"
if let date = df.date(from: str.prefix(11) + "12:00") {
print(date.description(with: .current))
}
// Friday, September 28, 2018 at 12:00:00 PM Brasilia Standard Time

Resources