This question already has answers here:
Date Format in Swift
(24 answers)
Closed 2 years ago.
I have a date of type date and has a format "yyyy-MM-dd HH:mm:ss" and I would like to convert it to "yyyy-MM-dd". I am not sure how to achieve this since the date is of type Date.
Example :
let dateComponents: Date? = dateFormatterGet.date(from: "2019-03-11 17:01:26")
Required output :
Date object of format type "yyyy-MM-dd"
It is important to note that I have only date objects and no string.
You have a date of type String, not Date.
You use one DateFormatter to convert it to Date (check that the DateFormatter doesn't return nil).
Then you use another DateFormatter to convert the Date to a string.
Please don't use "dateComponents" as a variable name. You never, ever touch date components in your code. And you don't need to specify the type, just "let date = ..." or better "if let date = ..." checking for nil.
you can use like this:
let now = Date().UTCToLocalDateConvrt(format: "yyyy-MM-dd HH:mm:ss",convertedFormat : "yyyy-MM-dd")
put below function in Date extension class:
extension Date {
func UTCToLocalDateConvrt(format: String,convertedFormat: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let timeStamp = dateFormatter.string(from: self)
dateFormatter.dateFormat = convertedFormat
guard let date = dateFormatter.date(from: timeStamp)else{
return Date()
}
return date
}
}
func formatDate(yourDate: String) -> String { // "yyyy-MM-dd HH:mm:ss"
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss" // here you can change the format that enters the func
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "yyyy-MM-dd" // here you can change the format that exits the func
if let date = dateFormatterGet.date(from: yourDate) {
return dateFormatterPrint.string(from: date)
} else {
return nil
}
}
use it like this:
formatDate(yourDate: "2019-03-11 17:01:26")
it will return an optional string, that can be nil, make sure you are safety unwrap it (if let , guard let)
answer based on link
Related
This question already has an answer here:
DateFormatter doesn't return date for "HH:mm:ss"
(1 answer)
Closed 2 years ago.
I have some troubles parsing string date to Date format.
I recibe from one API the date string with this format 2020-08-27 12:39:32 (the date come in 24 hour format) and I have an extension of String to convert it to Date. So I do the convertion like this:
apiTime.toDate(format: "yyyy-MM-dd HH:mm:ss")
All works fine if the phone is configured with 24 hour. The problem came when the app runs in a AM/PM date format because the date return nil.
This is my extension to convert String to Date.
extension String {
func toDate(format: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.amSymbol = "AM"
dateFormatter.pmSymbol = "PM"
dateFormatter.dateFormat = format
return dateFormatter.date(from: self) //here return nil with AM/PM format
}
}
As suggested by #LeoDabus it's better not to create DateFormatter every time (this is very resource-consuming). You can extract it, eg. as a static property.
Here is a simple demo:
class Test {
static let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
return dateFormatter
}()
func parseDateExample() {
let apiTime = "2020-08-27 12:39:32"
if let date = apiTime.toDate(formatter: Self.dateFormatter, format: "yyyy-MM-dd HH:mm:ss") {
print(date)
} else {
print("error")
}
}
}
You can reuse the formatter in your String extension instead of creating a new one every time you call toDate:
extension String {
func toDate(formatter: DateFormatter, format: String) -> Date? {
formatter.dateFormat = format
return formatter.date(from: self)
}
}
I trying to convert date from one format to another. But the date in the below code is coming as nil. Can you guys help me out below is the code.
func eventTimeDate() -> Date {
let dtf = DateFormatter()
dtf.timeZone = TimeZone.current
dtf.dateFormat = "yyyy-MM-dd HH:mm:ss z"
/// "2020-05-28 00:20:00 GMT+5:30"
let stringDate = dtf.string(from: self)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss z"
/// nil
let date = dateFormatter.date(from: stringDate)
return date!
}
If you need to convert from one formatted date string to another formatted date string, you can use two DateFormatters: one - an input formatter to convert a String to an intermediary Date object, and then - using an output formatter - convert from Date to String.
func reFormat(from dateStr: String) -> String? {
let fromFormatter = DateFormatter()
fromFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"
let toFormatter = DateFormatter()
toFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss z"
guard let date = fromFormatter.date(from: dateStr) else { return nil }
return toFormatter.string(from: date)
}
If you just need to return a Date object, then it's a simpler function using just one DateFormatter:
func toDate(from dateStr: String) -> Date? {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"
return formatter.date(from: dateStr)
}
Date object itself has no formatting - it's a pure representation of a date & time, which you can convert to/from using different formatters.
A swift class Date has no format.
In your code your stringDate is in "yyyy-MM-dd HH:mm:ss z" format. If you need to convert String to Date you must use the same format otherwise it will return nil.
If you want to change a format of a string then first convert it to a Swift 'Date' then again convert it to a string with the use of new Formatter.
func eventTimeDate(dateString : String, currentFormat : String, newFormat : String) -> String? {
let currentDateFormatter = DateFormatter()
currentDateFormatter.calendar = Calendar(identifier: Calendar.Identifier.gregorian)
currentDateFormatter.locale = Locale(identifier: "en_IN")
currentDateFormatter.dateFormat = currentFormat
let date = currentDateFormatter.date(from: dateString)
let newDateFormatter = DateFormatter()
newDateFormatter.calendar = Calendar(identifier: Calendar.Identifier.gregorian)
newDateFormatter.locale = Locale(identifier: "en_IN")
newDateFormatter.dateFormat = newFormat
if let date = date {
let newDateString = newDateFormatter.string(from: date)
return newDateString
}
return nil
}
You have three problems in your code. First when parsing a fixed date format you should always set the date formatter's locale to "en_US_POSIX". Second you need to escape the GMT of your date string. Last but not least important you need to fix your timezone string which it is missing the leading zero for your timezone hour:
let dateStr = "2020-05-28 00:20:00 GMT+5:30"
let formatter = DateFormatter()
// set the date formatter's locale to "en_US_POSIX"
formatter.locale = .init(identifier: "en_US_POSIX")
// escape the GMT of your date string
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss 'GMT'Z"
// add the leading zero for your timezone hour
let string = dateStr.replacingOccurrences(of: "(GMT[+-])(\\d:)", with: "$10$2", options: .regularExpression)
if let date = formatter.date(from: string) {
print(date) // "2020-05-27 18:50:00 +0000\n"
}
I receive a timestamp from a JSON request, and I want to format it to a user-friendly format. Both the input, as the desired output are of type 'String'.
The format of the input timestamp is: 2020-03-07T12:18:26.347Z
Using the following code, I try to convert it to the desired format. But it will just output the value of Date(), indicating that the output of formatter.date(from: date) is nil.
What am I missing?
func convertDate(date: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "d-M-y, HH:mm"
let convertedDate = formatter.date(from: date) ?? Date()
return formatter.string(from: convertedDate)
}
Your dateFormat doesn't match the format of your input string. You want something like:
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
After struggling with it for hours, this answer, together with the date format information found here, I figured it out. I did previously not describe to the dateformatter how the input string would look.
func convertDate(date: String) -> String {
let dateFormatter = DateFormatter()
// This is important - we set our input date format to match our input string
// if the format doesn't match you'll get nil from your string, so be careful
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
//`date(from:)` returns an optional so make sure you unwrap when using.
let dateFromString: Date? = dateFormatter.date(from: date)
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy, HH:mm"
//Using the dateFromString variable from before.
let stringDate: String = formatter.string(from: dateFromString!)
return stringDate
}
I'm storing some dates in coredata in Date format. In another viewcontroller, I want to retrieve those dates and convert them to string. I tried to achieve it like so...
if let bday = result.birthday {
print(bday)
let formatter = DateFormatter()
let bDateString = formatter.string(from: bday as Date)
print(bDateString)
self.birthdate = bDateString
}
Here, printing bday gives the proper date. But printing bDateString after converting to string gives nil. What am I doing wrong...?
Please provide format of date like this :
formatter.dateFormat = "MM-dd-yyyy" //provide your date format here
The issue is you have not provided date format.
Even you can use this extension
extension Date { static func getFormattedDate(string: String) -> String{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss +zzzz" // This formate is input formated .
let formateDate = dateFormatter.date(from:"2018-02-02 06:50:16 +0000")!
dateFormatter.dateFormat = "dd-MM-yyyy" // Output Formated
print ("Print :\(dateFormatter.string(from: formateDate))")//Print :02-02-2018
return dateFormatter.string(from: formateDate)
} }
I want this date "2016-10-18 22:06:20 +0000" to "18-10-2016", is this possible? I managed to get the date as follows:
var formatter = DateFormatter()
formatter.dateFormat = "yyy-MM-dd'HH:mm:ss.SSSZ"
let stringDate = formatter.string(from: currentDate)
The above gives me "10/18/16", but how can I get "18-10-2016"?
Solution in Swift 3
extension Foundation.Date {
func dashedStringFromDate() -> String {
let dateFormatter = DateFormatter()
let date = self
dateFormatter.dateFormat = "dd-MM-yyyy"
return dateFormatter.string(from: date)
}
}
Example
let date = Foundation.Date()
let formatedDate = date.dashedStringFromDate()
Little about what you put in your question makes a lot of sense. You don't have a date as 2016-10-18 22:06:20 +0000. The code you posted converts a current Date into a string. But you claim you want that string to be in the format 18-10-2016 but your code uses a completely different format.
Why not just do:
var formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
let stringDate = formatter.string(from: currentDate)
This will convert the currentDate to a string in the format you mention in your question.
If you really have a string in the format of 2016-10-18 22:06:20 +0000 and you want to convert it to 18-10-2016, then you want two date formatters.
The first convert that original string to a date:
let string = "2016-10-18 22:06:20 +0000"
let formatter1 = DateFormatter()
formatter1.locale = Locale(identifier: "en_US_POSIX") // if this string was from web service or a database, you should set the locale
formatter1.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
guard let date = formatter1.date(from: string) else {
fatalError("Couldn't parse original date string")
}
If you then want to build a new string in the format of 18-10-2016, then you'd use a second formatter:
let formatter2 = DateFormatter()
formatter2.dateFormat = "dd-MM-yyyy"
let result = formatter2.string(from: date)