I need to convert "2022-01-20T00:00:00.000Z" to "dd MMM yyy" format.
I have tried doing it as suggested in a stackoverflow answer but it returns nil
func convertDate(date:String)-> String{
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "dd MMM yyy"
if let date = dateFormatterGet.date(from: String(date)) {
let convertedDate = dateFormatterPrint.string(from: date)
return convertedDate
} else {
print("There was an error decoding the string")
}
return "nil"
}
The fractional seconds are missing in the date format string. It's yyyy-MM-dd'T'HH:mm:ss.SSSZ.
And you are not using the date parameter. To avoid confusion with the local variable date rename it.
And you don't need two date formatters and it's highly recommended to set the Locale to a fixed value
func convertDate(dateString: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let date = dateFormatter.date(from: dateString) {
dateFormatter.dateFormat = "dd MMM yyy"
return dateFormatter.string(from: date)
} else {
print("There was an error decoding the string")
return ""
}
}
got the answer
func convertDate(date:String)-> String{
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.sssZ"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "dd MMM yyy"
if let date = dateFormatterGet.date(from: String(date)) {
let convertedDate = dateFormatterPrint.string(from: date)
return convertedDate
} else {
print("There was an error decoding the string")
}
return "nil"
}
print(convertDate(date: "2022-01-20T00:00:00.000Z"))
In my scenario, I am trying to convert date time string one format to another format 26 Nov, 2019 - 2:53 AM to yyyy-MM-dd h:mm:ss. How to cover the format?
Below Code Returning Empty
let dateString = "26 Nov, 2019 - 2:53 AM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm a"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateres = dateFormatter.date(from: dateString)
print(dateres)
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")
Try This
Step 1:- Put this function on your class file
func convertDate(date: String, dateFormat : String, convertFormat : String) -> String {
let datetimeFormatOriginal = DateFormatter()
datetimeFormatOriginal.dateFormat = dateFormat
let convertedFormat = DateFormatter()
convertedFormat.dateFormat = convertFormat
if date == "" || date == "-" {
return "-"
}
else {
return convertedFormat.string(from: datetimeFormatOriginal.date(from: date)!)
}
}
Step:- 2 Now using this function convert date
let convertedDate = convertDate(date: "26 Nov, 2019 - 2:53 AM", dateFormat: "dd MMM, yyyy - HH:mm aa", convertFormat: "yyyy-MM-dd hh:mm a")
print(convertedDate)
OUTPUT
"2019-11-26 12:53 AM"
I am trying to change date time concatenation and changing string input format to another format. I tried below code. Here, I can able to change the date format but need to concatenate current time before passing input date string.
My Code Below
override func viewDidLoad() {
super.viewDidLoad()
let result = formattedDateFromString(dateString: "28 Aug, 2019", withFormat: "dd-MM-yyyy")
self.resultLabel.text = result
}
func formattedDateFromString(dateString: String, withFormat format: String) -> String? {
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "dd/MM/yyyy"
if let date = inputFormatter.date(from: dateString) {
let outputFormatter = DateFormatter()
outputFormatter.dateFormat = format
return outputFormatter.string(from: date)
}
return nil
}
Expected output like :
28-08-2019 5:00 PM
func formattedDateFromString(dateString: String, withFormat format: String) -> String? {
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "dd MMM, yyyy"
if let date = inputFormatter.date(from: dateString) {
print(date)
let outputFormatter = DateFormatter()
outputFormatter.dateFormat = format
return outputFormatter.string(from: date)
} else {
print("nope")
}
return nil
}
let result = formattedDateFromString(dateString: "28 Aug, 2019", withFormat: "dd-MM-yyyy - h:mm a")
print(result)
Outputs:
"28-08-2019 - 12:00 AM"
In general I found this website to be really useful when trying to reason about dates in Swift/Objective-C
You can use this function
func convDate(dateToConvert: String) -> String? {
//Input Format
let df = DateFormatter()
df.dateFormat = "dd LL, YYYY"
//Convert input date string to date
guard let date = df.date(from: dateToConvert) else { print("Incorrect date format"); return nil }
//Output format
let outDF = DateFormatter()
outDF.dateFormat = "dd-MM-YYYY"
let hourDF = DateFormatter()
hourDF.dateFormat = "h:mm a"
hourDF.amSymbol = "AM"
hourDF.pmSymbol = "PM"
//format to string dd-MM-YYYY H:mm a
return outDF.string(from: date) + " " + hourDF.string(from: Date())
}
example
print(convDate(dateToConvert: "13 Aug, 2019"))
I'm trying to convert a string to NSDate here is my code
let strDate = "2015-11-01T00:00:00Z" // "2015-10-06T15:42:34Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-ddTHH:mm:ssZ"
print ( dateFormatter.dateFromString( strDate ) )
I keep getting nil as a result
The "T" in the format string needs to be single quoted so it will not be consider a symbol:
Swift 3.0
let strDate = "2015-11-01T00:00:00Z"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:strDate)
print("date: \(date!)")
Output:
date: 2015-11-01 00:00:00 +0000
Swift 2.x
let strDate = "2015-11-01T00:00:00Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.dateFromString(strDate)
print("date: \(date!)")
Output:
date: 2015-11-01 00:00:00 +0000
See: Date Field SymbolTable.
This includes the need to enclose ASCII letters in single quotes if they are intended to represent literal text.
For swift 4 and swift 3.2 updated answer.
here all Date related function mentioned.
hop these function useful for you.
1=> Timestamp to Date
func timeStampToDate(_timestamp : String, _dateFormat : String) -> String{
var LOCAL_TIME_ZONE: Int { return TimeZone.current.secondsFromGMT() }
var date = Date(timeIntervalSince1970: TimeInterval(_timestamp)!)
date += TimeInterval(LOCAL_TIME_ZONE as NSNumber)
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "GMT") //Set timezone that you want
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = _dateFormat //Specify your format that you want
let strDate = dateFormatter.string(from: date)
return strDate
}
2=> Date to String
func DateToString(date : Date, dateFormatte : String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormatte
print("Dateobj: (dateFormatter.string(from: dateObj!))")
return (dateFormatter.string(from: date as Date))
}
3=> String to date
func StringDateToDate(dateString : String, dateFormatte : String) -> Date {
//let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
//let dateFormatte = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormatte
let dateObj = dateFormatter.date(from: dateString)
if dateObj == nil {
return Date()
}
return dateObj!
}
I want to convert "2014-07-15 06:55:14.198000+00:00" this string date to NSDate in Swift.
try this:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = /* find out and place date format from
* http://userguide.icu-project.org/formatparse/datetime
*/
let date = dateFormatter.dateFromString(/* your_date_string */)
For further query, check NSDateFormatter and DateFormatter classes of Foundation framework for Objective-C and Swift, respectively.
Swift 3 and later
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = /* date_format_you_want_in_string from
* http://userguide.icu-project.org/formatparse/datetime
*/
guard let date = dateFormatter.date(from: /* your_date_string */) else {
fatalError("ERROR: Date conversion failed due to mismatched format.")
}
// use date constant here
Edit:
Alternative date time format reference
https://unicode-org.github.io/icu/userguide/format_parse/datetime/
Swift 4
import Foundation
let dateString = "2014-07-15" // change to your date format
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: dateString)
println(date)
Swift 3
import Foundation
var dateString = "2014-07-15" // change to your date format
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var date = dateFormatter.dateFromString(dateString)
println(date)
I can do it with this code.
func convertDateFormatter(date: String) -> String
{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date = dateFormatter.dateFromString(date)
dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"///this is what you want to convert format
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let timeStamp = dateFormatter.stringFromDate(date!)
return timeStamp
}
Updated for Swift 3.
func convertDateFormatter(date: String) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let date = dateFormatter.date(from: date)
dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"///this is what you want to convert format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let timeStamp = dateFormatter.string(from: date!)
return timeStamp
}
Details
Swift 4, Xcode 9.2
Swift 5, Xcode 10.2 (10E125)
Solution
import Foundation
extension DateFormatter {
convenience init (format: String) {
self.init()
dateFormat = format
locale = Locale.current
}
}
extension String {
func toDate (dateFormatter: DateFormatter) -> Date? {
return dateFormatter.date(from: self)
}
func toDateString (dateFormatter: DateFormatter, outputFormat: String) -> String? {
guard let date = toDate(dateFormatter: dateFormatter) else { return nil }
return DateFormatter(format: outputFormat).string(from: date)
}
}
extension Date {
func toString (dateFormatter: DateFormatter) -> String? {
return dateFormatter.string(from: self)
}
}
Usage
var dateString = "14.01.2017T14:54:00"
let dateFormatter = DateFormatter(format: "dd.MM.yyyy'T'HH:mm:ss")
let date = Date()
print("original String with date: \(dateString)")
print("date String() to Date(): \(dateString.toDate(dateFormatter: dateFormatter)!)")
print("date String() to formated date String(): \(dateString.toDateString(dateFormatter: dateFormatter, outputFormat: "dd MMMM")!)")
let dateFormatter2 = DateFormatter(format: "dd MMM HH:mm")
print("format Date(): \(date.toString(dateFormatter: dateFormatter2)!)")
Result
More information
About date format
If you're going to need to parse the string into a date often, you may want to move the functionality into an extension. I created a sharedCode.swift file and put my extensions there:
extension String
{
func toDateTime() -> NSDate
{
//Create Date Formatter
let dateFormatter = NSDateFormatter()
//Specify Format of String to Parse
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx"
//Parse into NSDate
let dateFromString : NSDate = dateFormatter.dateFromString(self)!
//Return Parsed Date
return dateFromString
}
}
Then if you want to convert your string into a NSDate you can just write something like:
var myDate = myDateString.toDateTime()
For Swift 3
func stringToDate(_ str: String)->Date{
let formatter = DateFormatter()
formatter.dateFormat="yyyy-MM-dd hh:mm:ss Z"
return formatter.date(from: str)!
}
func dateToString(_ str: Date)->String{
var dateFormatter = DateFormatter()
dateFormatter.timeStyle=DateFormatter.Style.short
return dateFormatter.string(from: str)
}
The code fragments on this QA page are "upside down"...
The first thing Apple mentions is that you cache your formatter...
Link to Apple doco stating exactly how to do this:
Cache Formatters for Efficiency
Creating a date formatter is not a cheap operation. ...cache a single instance...
Use a global...
let df : DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
Then simply use that formatter anywhere...
let s = df.string(from: someDate)
or
let d = df.date(from: someString)
Or use any of the other many, many convenient methods on DateFormatter.
It is that simple.
(If you write an extension on String, your code is completely "upside down" - you can't use any dateFormatter calls!)
Note that usually you will have a few of those globals .. such as "formatForClient" "formatForPubNub" "formatForDisplayOnInvoiceScreen" .. etc.
Swift support extensions, with extension you can add a new functionality to an existing class, structure, enumeration, or protocol type.
You can add a new init function to NSDate object by extenging the object using the extension keyword.
extension NSDate
{
convenience
init(dateString:String) {
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "yyyyMMdd"
dateStringFormatter.locale = NSLocale(localeIdentifier: "fr_CH_POSIX")
let d = dateStringFormatter.dateFromString(dateString)!
self.init(timeInterval:0, sinceDate:d)
}
}
Now you can init a NSDate object using:
let myDateObject = NSDate(dateString:"2010-12-15 06:00:00")
Since Swift 3, many of the NS prefixes have been dropped.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
/* date format string rules
* http://userguide.icu-project.org/formatparse/datetime
*/
let date = dateFormatter.date(from: dateString)
Swift 3,4:
2 useful conversions:
string(from: Date) // to convert from Date to a String
date(from: String) // to convert from String to Date
Usage:
1.
let date = Date() //gives today's date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy"
let todaysDateInUKFormat = dateFormatter.string(from: date)
2.
let someDateInString = "23.06.2017"
var getDateFromString = dateFormatter.date(from: someDateInString)
FOR SWIFT 3.1
func convertDateStringToDate(longDate: String) -> String{
/* INPUT: longDate = "2017-01-27T05:00:00.000Z"
* OUTPUT: "1/26/17"
* date_format_you_want_in_string from
* http://userguide.icu-project.org/formatparse/datetime
*/
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.date(from: longDate)
if date != nil {
let formatter = DateFormatter()
formatter.dateStyle = .short
let dateShort = formatter.string(from: date!)
return dateShort
} else {
return longDate
}
}
NOTE: THIS WILL RETURN THE ORIGINAL STRING IF ERROR
To add String within Date Format in Swift, I did this
var dataFormatter:NSDateFormatter = NSDateFormatter()
dataFormatter.dateFormat = "dd-MMMM 'at' HH:mm a"
cell.timeStamplbl.text = dataFormatter.stringFromDate(object.createdAt)
This work for me..
import Foundation
import UIKit
//dateString = "01/07/2017"
private func parseDate(_ dateStr: String) -> String {
let simpleDateFormat = DateFormatter()
simpleDateFormat.dateFormat = "dd/MM/yyyy" //format our date String
let dateFormat = DateFormatter()
dateFormat.dateFormat = "dd 'de' MMMM 'de' yyyy" //format return
let date = simpleDateFormat.date(from: dateStr)
return dateFormat.string(from: date!)
}
You can try this swift code
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"//same as strDate date formator
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00")//Must used if you get one day less in conversion
let convertedDateObject = dateFormatter.date(from: strDate)
Below are some string to date format converting options can be usedin swift iOS.
Thursday, Dec 27, 2018 format= EEEE, MMM d, yyyy
12/27/2018 format= MM/dd/yyyy
12-27-2018 09:59 format= MM-dd-yyyy HH:mm
Dec 27, 9:59 AM format= MMM d, h:mm a
December 2018 format= MMMM yyyy
Dec 27, 2018 format= MMM d, yyyy
Thu, 27 Dec 2018 09:59:19 +0000 format= E, d MMM yyyy HH:mm:ss Z
2018-12-27T09:59:19+0000 format= yyyy-MM-dd'T'HH:mm:ssZ
27.12.18 format= dd.MM.yy
09:59:19.815 format= HH:mm:ss.SSS
SWIFT 5, Xcode 11.0
Pass your (date in string) in "dateString" and in "dateFormat" pass format you want. To choose format, use NDateFormatter website.
func getDateFrom(dateString: String, dateFormat: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatter.locale = Locale(identifier: "en_US")
guard let date = dateFormatter.date(from: dateString) else {return nil}
return date
}
Swift: iOS
if we have string, convert it to NSDate,
var dataString = profileValue["dob"] as String
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
// convert string into date
let dateValue:NSDate? = dateFormatter.dateFromString(dataString)
if you have and date picker parse date like this
// to avoid any nil value
if let isDate = dateValue {
self.datePicker.date = isDate
}
import Foundation
let now : String = "2014-07-16 03:03:34 PDT"
var date : NSDate
var dateFormatter : NSDateFormatter
date = dateFormatter.dateFromString(now)
date // $R6: __NSDate = 2014-07-16 03:03:34 PDT
https://developer.apple.com/library/prerelease/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/index.html#//apple_ref/doc/uid/20000447-SW32