dateFromString() returns incorrect date - swift

I'm trying to convert string to Date, but it result incorrect date.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMM YYYY"
let dt = dateFormatter.dateFromString("17 Sep 2015")
println("Date : \(dt)")
It result
Date : Optional(2014-12-20 18:30:00 +0000)
Please let me know where I'm making mistake. I tried other format too, but it return nil.

The format for year is incorrect, it should be yyyy, not YYYY.
"Y": Year (in "Week of Year" based calendars). This year designation is used in ISO year-week calendar as defined by ISO 8601, but can be used in non-Gregorian based calendar systems where week date processing is desired. May not always be the same value as calendar year.
See: Date Field SymbolTable.
Also: ICU Formatting Dates and Times

Your date format string is wrong. Change it to the following:
dateFormatter.dateFormat = "dd MMM yyyy"
For more information read Date Formatters documentation.

Related

How to parse date in "2022-03-04T10:30:00-08:00" format correctly in swift?

I have date coming from API shown below. These dates are for different countries.
dateTime = "2022-03-04T14:30:00-08:00"
I need to convert this use it both as Date and as String. But I do not know if date and time I am converting are correct. I am using following code:
To Convert String from API to Date:
extension String {
var CommonDateFormat: Date? {
get {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return dateFormatter.date(from: self)
}
}
}
To Convert Date to String:
extension Date {
func getDateAccoringTo(format: DateFormat ) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format.rawValue
dateFormatter.timeZone = .current
dateFormatter.timeZone = TimeZone.init(identifier: "UTC")
return dateFormatter.string(from: self)
}
}
enum DateFormat: String {
case ddmmyyyy = "dd/MM/yyyy"
case mmddyyyy = "MM/dd/yyyy"
case mmmd_yyyy = "MMM d, yyyy"
case llll_yyyy = "LLLL ,yyyy"
case TIME = "HH:mm:ss"
case day = "dd"
}
When I try to get day from date it always gives next day date. For example if date = "2022-03-04T14:30:00-08:00" then if I try to get day using code below
date?.getDateAccoringTo(format: .day)
This returns 5 not 4
date?.getDateAccoringTo(format: .TIME)
This returns time 00:00:00
Am I missing something important which is leading to these values?
Also, if I am missing something in my question kindly let me know so that I can improve it.
The given string
let dateTime = "2022-03-04T14:30:00-08:00"`
is a standard ISO8601 formatted date string. It can be converted to Date with
let formatter = ISO8601DateFormatter()
let date = formatter.date(from: dateTime)!
At this specific point in time it is
14:30 on Friday, March 4 in Denver, CO, USA
22:30 on Friday, March 4 in London, UK
06:30 on Saturday, March 5 in Tokyo, Japan
Now let's see how Xcode displays dates.
print displays Date instances always in UTC indicated by +0000 which is the London time zone unless you print(date.description(with: .current), this displays the date in the local time zone.
In a Xcode Playground the result area displays Date instances in the local time zone except in print lines.
Last point to consider is that DateFormatter converts Date to String in the local time zone if no time zone is specified.
Keeping this behavior in mind you get the next day if you convert the date to string with DateFormatter but without specifying the time zone and your local time zone is greater than or equal to +01:30.
And you get the time 00:00 if you convert the date to string with DateFormatter but without specifying the time zone and your local time zone is exactly +01:30 which is a pretty unusual time zone by the way.

Swift Convert date string to Date

I got a date string from server side, which is Tue, 28 May 2019 13:24:06 +0000. I tried to do following:
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
let date = dateFormatter.date(from: "Tue, 28 May 2019 13:24:06 +0000")
result is nil
How can I convert a string like this to a Date?
You need to set a specific dateFormat. And when doing so, set the date formatter's locale to en_US_POSIX.
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
let date = dateFormatter.date(from: "Tue, 28 May 2019 13:24:06 +0000")
See the documentation for dateFormat for links that take you a full description of what all of the format specifiers mean.
Keep in mind that when converting a Date to a String for display to the user, then using date and time styles is the best solution. But for parsing a String into a Date, use dateFormat.

Date Formatter isn't showing correct day of the month when using format "DD"

I am trying to show today's date as March 26 but it is showing as "March 85" when I use this code.
let formatter = DateFormatter()
formatter.dateFormat = "MMMM DD"
let defaultTimeZoneStr = formatter.string(from: Date())
The problem is that you are using the wrong date format. D is for "day of year". The correct symbol for "day of month" is lowercased d Thats why you are getting 85instead of 26.
Another point you should consider is to set your locale fixed to "en_US_POSIX" if you don't want your date string to reflect the users settings and locale.
Note that you should use Swift native type Date instead of NSDate.
If your intent is to display it respecting the user locale and settings you should use date formatter dateStyle (short, medium, long or full) How do I get the current Date in short format in Swift
If you need a localized date format limited to
month and day only, you can use DateFormatter method dateFormat from template:
class func dateFormat(fromTemplate tmplate: String, options opts: Int, locale: Locale?) -> String?
let df = DateFormatter()
df.dateFormat = DateFormatter.dateFormat(fromTemplate: "MMMMdd", options: 0, locale: .current)
df.string(from: Date()) // "March 27"

How to convert milliseconds to local day, date and time format in swift?

I want to display the date in this format (Wed Jan 10 2018 11:20:17). How to convert milliseconds to this format in swift?I want to get the day as Wed, time as 10:30 AM or PM and the date as 10 Jan.
First convert it in date by dividing it by 1000
var date = Date(timeIntervalSince1970: (1477593000000 / 1000.0))
then use DateFormatter to convert in desired format you need
Note: Not tested in XCODE
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss"
print(dateFormatter.string(from: date))
Hope it is helpful to you.

New month date continues to count up

The new month of Feburary date continues to count up from January. So instead of showing Feburary 1St, it's showing Feburary 32 Like the picture below, any help would be appreciated thanks.
This is how I am getting the current date:
let date = Date()
let format = DateFormatter()
format.dateFormat = "EE, MMM DD, YYYY"
let currentDate = format.string(from: date)
header.headerTitle.text = currentDate
This is the result Feburary 32, 2018
Change "EE, MMM DD, YYYY" to "EE, MMM dd, yyyy" (or maybe just one d) and next time please try to read up on how date formatters work before trying to use them:
http://userguide.icu-project.org/formatparse/datetime