How to convert date format from dd/MM/YYYY to YYYY-MM-dd in swift
First changes your year
formatter with yyyy
and instead of using two NSDateFormatter
use just one like this
let inputFormatter = NSDateFormatter()
inputFormatter.dateFormat = "MM/dd/yyyy"
let showDate = inputFormatter.dateFromString("07/21/2016")
inputFormatter.dateFormat = "yyyy-MM-dd"
let resultString = inputFormatter.stringFromDate(showDate!)
print(resultString)
For Swift3 and later
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let date = dateFormatter.date(from: date)
dateFormatter.dateFormat = "yyyy-MM-dd"
let resultString = dateFormatter.string(from: date!)
print(resultString)
How to convert string date time format to another format using Swift
extension String {
func convertToDateFormate(current: String, convertTo: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = current
guard let date = dateFormatter.date(from: self) else {
return self
}
dateFormatter.dateFormat = convertTo
return dateFormatter.string(from: date)
}
}
convert to required formate as
let dateString = "12-10-2019"
let convertedDate = dateString.convertToDateFormate(current: "dd-MM-YYYY", convertTo: "YYYY-MM-dd")
Swift date format returning wrong date
The code in your question is muddled up. You try to convert a string into a string in the first example and something unspecified into a Date
in the second example.
Here's how to convert a Date
into a String
:
import Foundation
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
let string: String = formatter.string(from: Date())
print(string) // prints for example 2020-10-18T10:54:07+01:00
Here's how to convert a string into a date
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ssZ"
let date: Date = formatter.date(from: "2020-10-18 10:59:56+0100")! // In real life, handle the optional properly
print(date) // prints 2020-10-18 09:59:56 +0000
When you print a Date directly, it automatically uses UTC as the time zone. This is why it changed it in the code above.
In the examples, I explicitly specified the type of string
and date
to show what type they are. Type inference means you can omit these in normal code.
As a general rule when handling dates:
- always use
Date
in your code.Date
is a type that stores the number of seconds since Jan 1st 1970 UTC. - Only convert dates to strings when displaying them to the user or communicating with an external system.
- When calculating periods etc, always use a Calendar to get things like date components and intervals in units other than seconds. You might think to get "the same time tomorrow" you could just add 24 * 60 * 60 to a
Date
but in many countries, like mine, that will work on only 363 days in the year.Calendar
will correctly handle things like daylight saving and leap years.
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")
}
Can't Convert Date Format Into Display Date In Swift
You should always set your dateFormat locale to "en_US_POSIX"
before setting the dateFormat. Btw it looks like that your date string you are reading from database is always in UTC format, if that is the case you should set your dateFormatter timezone to zero secondsFromGMT and escape your date string timezone:
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSSIX")
dateFormatter.dateFormat = "EEE MMM dd yyyy HH:mm:ss 'GMT+0000 (Greenwich Mean Time)'"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.date(from: "Thu Nov 12 2020 07:00:00 GMT+0000 (Greenwich Mean Time)")
You should also create a static date formatter to avoid creating a new one every time you call this method:
extension Formatter {
static let customDate: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSSIX")
dateFormatter.dateFormat = "EEE MMM dd yyyy HH:mm:ss 'GMT+0000 (Greenwich Mean Time)'"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
return dateFormatter
}()
static let yyyyMMMd: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.setLocalizedDateFormatFromTemplate("yyyyMMMd")
return dateFormatter
}()
}
extension String {
func convertToDate() -> Date? {
Formatter.customDate.date(from: self)
}
func convertToDisplayFormat() -> String {
convertToDate()?.convertToMonthDayTimeFormat() ?? "N/A"
}
}
extension Date {
func convertToMonthDayTimeFormat() -> String {
Formatter.yyyyMMMd.string(from: self)
}
}
Playground testing:
"Thu Nov 12 2020 07:00:00 GMT+0000 (Greenwich Mean Time)".convertToDisplayFormat() // "Nov 12, 2020"
How to change date format from dd MMMM YYYY in swift?
Using DateFormatter
is right way to do. First you need to convert the 01 August 2021
, String
type, to Date
object. Second, change dateFormat
and re-format it. Here is tested code for both of your need:
func convert(_ dateString: String, from initialFormat: String, to targetFormat: String? = nil, _ locale: Locale? = nil) -> String? {
let formatter = DateFormatter()
formatter.dateFormat = initialFormat
guard let date = formatter.date(from: dateString) else { return nil }
if let newFormat = targetFormat {
formatter.dateFormat = targetFormat
}
formatter.locale = locale
return formatter.string(from: date)
}
print(convert("01 August 2021", from: "dd MMMM yyyy", .init(identifier: "id_ID")))
print(convert("01 August 2021", from: "dd MMMM yyyy", to: "dd-MM-yyyy"))
Swift Convert Date to Date with dateFormat
Answer to your question: No.
You can create a date/string extension, that can solve your problem in one-line. Note, Date
object is a date object. It does not have any format (like string).
May this help you:
extension String {
func convertDateString() -> String? {
return convert(dateString: self, fromDateFormat: "yyyy-MM-dd'T'HH:mm:ssZ", toDateFormat: "yyyy-MM-dd")
}
func convert(dateString: String, fromDateFormat: String, toDateFormat: String) -> String? {
let fromDateFormatter = DateFormatter()
fromDateFormatter.dateFormat = fromDateFormat
if let fromDateObject = fromDateFormatter.date(from: dateString) {
let toDateFormatter = DateFormatter()
toDateFormatter.dateFormat = toDateFormat
let newDateString = toDateFormatter.string(from: fromDateObject)
return newDateString
}
return nil
}
}
Use one-line code:
let newDateString = "my date string".convertDateString()
Related Topics
Randomize Two Arrays the Same Way Swift
Spritekiit Swift: Touch a Moving Object
Firebase Datadescription Returns Empty Array
How to Make a Uiview Grow in Uiview.Animate() with an Accurate Corner Radius
Fetch an Email Body in Mailcore2 Osx with Swift
How to Generate a Random Unicode Character in Swift
Make Swiftui Rectangle Same Height or Width as Another Rectangle
How to Convert This Date Format in Swift
Decode/Encode Dictionary Keyed by Date
Handle Single Click and Double Click While Updating the View
How to Set Up Multiple Combine Timer Publishers
Updating Switfui View When Coredata Changes
Failable Initializers with Codable
Where to Implement Nsvaluetransformer for Core Data in Swift
Why Function Return Nil Firebase Swift
Updated Approach to Reauthenticate a User
Does _Arraytype or _Arrayprotocol Not Available in Swift 3.1