Did SWIFT DateFormatter.dateFormat formatting change? - swift

I recently noticed my DateFormatter is no longer working with am/pm format. Did Swift recently change "h" and "a" dateFormat symbols? Could it be another setting I may have recently changed and am not seeing?
let formatt = DateFormatter()
formatt.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateDater = formatt.date(from:"2019-03-16 14:00:00")
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yy hh:mm a"
let string = formatter.string(from:dateDater!)
print("DateString",string)
Result: DateString 03/16/19 14:00

Unless you prevent it, formatting depends on the user Locale. So it all depends on your regional and date time settings, such as this one:
And this one:
For more info, read https://developer.apple.com/library/archive/qa/qa1480/_index.html

Related

I want to format a date into a string, but its giving me nil, i want to use the date in a UITextField.text

// the creationdate is coming from an api call
var creationDate = "2020-11-04T16:46:59.439212Z"
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeStyle = .none
formatter.dateFormat = "dd-MM-yyyy"
var creationDateFormattedInToDate = formatter.date(from:
creationDate)
print("date \(creationDateFormattedInToDate)")
So i want that date in the format 04-11-2020 and pass in a UITextField.text
You will need two formatters, one to parse the input date to a Date object and one to convert the date object to a string of the right format.
The input date seems to be a variant of a internet date/time so we use a ISO8601DateFormatter
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
The second formatter is a basic DateFormatter with a custom format
let outputFormatter = DateFormatter()
outputFormatter.dateFormat = "dd-MM-yyyy"
And then we can use them like this
if let date = formatter.date(from: creationDate) {
someTextField.text = outputFormatter.string(from: date)
}
You will want to use one formatter for parsing the response from the server (which is in what’s called and “ISO 8601” or “RFC 3339” format), and another for preparing the string representation of the date in the UI.
Regarding the date formatter for parsing the server response:
Set the formatter’s locale to Locale(identifier: "en_US_POSIX").
The setting of the styles when parsing this date string are irrelevant if you’re going to set dateFormat.
When parsing the date from the string, set dateFormat to yyyy-MM-dd'T'HH:mm:ss.SSSSSSX.
If you ever plan on using this formatter for the reverse date-to-string conversion (for preparing date strings to be sent to the server) you might want to set the timeZone of the formatter to TimeZone(secondsFromGMT: 0).
Regarding the date formatter used to prepare the string representation of the date in your UI:
I would not advise ever using a fixed dd-MM-yyyy format in your UI. That might be natural for European users, but it may be unnatural to most US users, who generally expect to see month before the day.
I would suggest not using dateFormat for this second date formatter, but rather using a dateStyle (e.g. of .medium or .long). It results in a nice, localized, and natural reading date string.
If you insist in using dd and MM and yyyy in your UI, I’d localize it with setLocalizedDateFormatFromTemplate so that the day and the month appear in the logical order that this particular user would expect (month-followed-by-day for US users, day-followed-by-month for most other locales).
Thus:
let serverDateFormatter = DateFormatter()
serverDateFormatter.locale = Locale(identifier: "en_US_POSIX")
serverDateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
serverDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSX"
let uiFormatter = DateFormatter()
uiFormatter.dateStyle = .medium // or uiFormatter.setLocalizedDateFormatFromTemplate("ddMMyyyy")
if let date = serverDateFormatter.date(from: creationDateString) {
let string = uiFormatter.string(from: date)
// use that `string` in your UI
}

Swift: How to parse date & time string with timezone abbreviation?

I receive a date & time string from a server with an information about a timezone formatted in an unusual way:
2017-05-05T12:24:16.286462Z[UTC]
I would like to use DateFormatter to parse it, but I cannot figure out what date format should I use.
I tried parsing it with "yyyy-MM-dd'T'HH:mm:ss.SSSZ'['R']'" or something quite similar but with no luck.
Here is my code:
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en-US")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ'['R']'"
let date = dateFormatter.date(from: date)
What is the right date format for this string?
OK guys, I figured it out.
The right format is
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z['zzz']'"
zzz is for a timezone abbreviation, while Z[ and ] are treated as a plain text.
An alternative approach with ISO8601DateFormatter. The [UTC] portion is stripped with Regular Expression
let dateString = "2017-05-05T12:24:16.286462Z[UTC]"
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
let date = formatter.date(from: dateString.replacingOccurrences(of: "\\[^\\[+\\]", with: "", options: .regularExpression))

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"

Got nil after string to date convertation

I need to convert String simular to "2016-07-10T21:32:20G" to Date.
But for some reason I've got only nil again and again.
I've read an article about date formater. And unfortunately haven't fount an answer there. I found something in the documentation. And documentation tels to read about Unicode Date Format Patterns. And it looks similar to mine.
Probably I missed something =(
My Code example. Unfortunately always get nil.
let lastUpdatedDateString = "2016-07-10 21:32:20"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-mm-dd hh:mm:ss"
let lastUpdated = dateFormatter.date(from:lastUpdatedDateString)
But this code works fine:
let lastUpdatedDateString = "2016-07-10"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-mm-dd"
let lastUpdated = dateFormatter.date(from:lastUpdatedDateString)
I'm testing it in the playground.
In fact I must convert this String("2016-07-10T21:32:20G") to Date.
PS
Anyway, thanks for attention =)
Think it's just the capitalisation in your formatter. Try this ...
let lastUpdatedDateString = "2016-07-10 21:32:20"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let lastUpdated = dateFormatter.date(from:lastUpdatedDateString)
This is what I get with the playground
let lastUpdatedDateString = "2016-07-10T21:32:20"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-ddEEEEEHH:mm:ss"
let lastUpdated = dateFormatter.date(from:lastUpdatedDateString)
print(lastUpdated)
and it prints: Optional(2016-07-10 19:32:20 +0000) (I'm GMT+2)
I don't know what the G stands for so I'm not sure how I can get the last character for the pattern. EEEEE stands for day of the week (1 character)
EDIT: It seems G stand for gregorian calendar
so you can parse the last letter out of the string and add this if it's gregorian calendar (but I suppose this is the default value):
dateFormatter.calendar = Calendar(identifier: .gregorian)
If the letter's a J it's Julian calendar then and you can see this answer to see how to convert gregorian to julian: https://stackoverflow.com/a/12137019/2106940

Swift date formatting

I'm trying to pull a date string from a button and format is as a date to be store in CoreData.
Here is my code:
let dateStr = setDateBTN.titleLabel?.text
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-YYYY"
let date:NSDate = dateFormatter.dateFromString(dateStr!)!
If I do a println on dateStr I get the following: 03-10-2015. Then if I immediately println on date I get: 2014-12-21 05:00:00 +0000.
Any ideas as to why the actual date is changing when I run it through the date formatter?
NSDateFormatter Class Reference : http://goo.gl/7fp9gl
Date Formatting Guide (Apple) : http://goo.gl/8zRTQl
A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar.
Your code should work, as you expect, like this :
let dateStr = setDateBTN.titleLabel?.text
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let date:NSDate = dateFormatter.dateFromString(dateStr!)!