Set a datestyle in Swift
Thanks to type inference you can do this
dateFormatter.dateStyle = .medium
How to format date in 09-Nov-2014 format with DateFormatter in iOS & Swift?
Don't set the styles. Just set the format.
You use either dateFormat
or you use dateStyle
and timeStyle
.
Please note it's best to avoid using dateFormat
for dates you wish to show to the user since your hardcoded format won't be standard for most users.
Also be aware that MM
show the month number. If you want the abbreviated month name, use MMM
.
Date Format in Swift
You have to declare 2 different NSDateFormatters
, the first to convert the string to a NSDate
and the second to print the date in your format.
Try this code:
let dateFormatterGet = NSDateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatterPrint = NSDateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let date: NSDate? = dateFormatterGet.dateFromString("2016-02-29 12:24:26")
print(dateFormatterPrint.stringFromDate(date!))
Swift 3 and higher:
From Swift 3 NSDate
class has been changed to Date
and NSDateFormatter
to DateFormatter
.
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
if let date = dateFormatterGet.date(from: "2016-02-29 12:24:26") {
print(dateFormatterPrint.string(from: date))
} else {
print("There was an error decoding the string")
}
How do I make a day come first while using the dateStyle in Swift
You don't actually need to change anything in your code. Just switch your Simulator's Region (Settings -> General -> Language & Region) to a place that uses the little endian (day, month, year) style (here's a list). A typical example is the UK.
If you want to always show the day first, regardless of the user's region, you can set the locale
of the date formatter to one of those countries listed above:
dateFormatter.locale = Locale(identifier: "en-GB")
But I don't recommend this. You should not disrespect the user's language and region and their preferred date format unless you have a really good reason.
How to format dates in Swift?
The following will do. Note that I used stringFromDate
twice with different format strings, instead of splitting the formatted date as you wanted. Using stringFromDate
twice is more independent from the format.
Also creation of NSDateFormatter
is a bit expensive, it's best to reuse it.
let z = "2014-03-18T03:31:14.000Z"
let fmt = NSDateFormatter()
fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = fmt.dateFromString(z)!
fmt.timeZone = NSTimeZone(abbreviation: "Australia/Brisbane")
fmt.dateFormat = "yyyy-MM-dd"
let dateString = fmt.stringFromDate(date)
fmt.dateFormat = "h:mm a"
let timeString = fmt.stringFromDate(date)
print("date: \(dateString), time: \(timeString)")
Swift - Convert a short format string of a date to long format using date formatter
Removing the dateStyle
line fixes it, and an actual date is printed.
Code:
func stringToDate(dateString: String){
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd"
let newDate = formatter.date(from: dateString)
print("formatter: \(newDate)")
}
// Prints: formatter: Optional(2021-08-04 23:00:00 +0000)
To do the whole conversion, the following function will work:
func convertDate(from original: String) -> String? {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd"
guard let date = formatter.date(from: original) else { return nil }
formatter.dateStyle = .long
let string = formatter.string(from: date)
return string
}
// Prints: Optional("August 5, 2021")
Of course, this may be printed slightly different due to my location & language
The following line of code can only be run after getting a Date
otherwise you are 'overwriting' the dateFormat
:
formatter.dateStyle = .long
How can you make date formatter in Swift to show only the year part of the date?
If you need to define a format that cannot be achieved using the predefined styles, you can use the
setLocalizedDateFormatFromTemplate(_:)
to specify a localized date format from a template.Source: DateFormatter - Foundation
In your case:
dateFormatter.setLocalizedDateFormatFromTemplate("yyyy")
DateFormatter. Strange behaviour on iOS 13.4.1 while 12 hour date style set in the iOS settings
The problem is fixed. Locale needs to be set.
formatter.locale = Locale(identifier: "en_US_POSIX")
Related Topics
Firebase Query Containing Value
Round Top Corners of a Uiview in Swift
How to Get Day and Month from Date Type - Swift 4
How to Take Screen Shot Programmatically (Swift, Spritekit)
How to Determine If a Variable Passed in Is Reference Type or Value Type
Is String Type a Class or a Struct? or Something Else
Swift 4 Attributedstring Get Typing Attributes
Smooth Transition Between 2 Scrollviews
How to Edit the Uiblureffect Intensity
How to Concatenate Optional Swift Strings
Converting .M4A File to .Aiff Using Audioconverter Swift
How to Append a Character to a String in Swift
Load a Collada (Dae) File into Scnnode (Swift - Scenekit)