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 85
instead 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"