[ios] Convert NSDate to String in iOS Swift

I am trying to convert a NSDate to a String and then Change Format. But when I pass NSDate to String it is producing whitespace.

 let formatter = DateFormatter()
 let myString = (String(describing: date))
 formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
 let yourDate: Date? = formatter.date(from: myString)
 formatter.dateFormat = "dd-MMM-yyyy"
 print(yourDate)

This question is related to ios swift swift3 nsdateformatter

The answer is


you get the detail information from Apple Dateformatter Document.If you want to set the dateformat for your dateString, see this link , the detail dateformat you can get here for e.g , do like

let formatter = DateFormatter()
// initially set the format based on your datepicker date / server String
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

let myString = formatter.string(from: Date()) // string purpose I add here 
// convert your string to date
let yourDate = formatter.date(from: myString)
//then again set the date format whhich type of output you need
formatter.dateFormat = "dd-MMM-yyyy"
// again convert your date to string
let myStringafd = formatter.string(from: yourDate!)

print(myStringafd)

you get the output as

enter image description here


You can use this extension:

extension Date {

    func toString(withFormat format: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        let myString = formatter.string(from: self)
        let yourDate = formatter.date(from: myString)
        formatter.dateFormat = format

        return formatter.string(from: yourDate!)
    }
}

And use it in your view controller like this (replace <"yyyy"> with your format):

yourString = yourDate.toString(withFormat: "yyyy")

After allocating DateFormatter you need to give the formatted string then you can convert as string like this way

var date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
let updatedString = formatter.string(from: yourDate!)
print(updatedString)

OutPut

01-Mar-2017


Your updated code.update it.

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date as Date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
print(yourDate!)

Something to keep in mind when creating formatters is to try to reuse the same instance if you can, as formatters are fairly computationally expensive to create. The following is a pattern I frequently use for apps where I can share the same formatter app-wide, adapted from NSHipster.

extension DateFormatter {

    static var sharedDateFormatter: DateFormatter = {
        let dateFormatter = DateFormatter()   
        // Add your formatter configuration here     
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        return dateFormatter
    }()
}

Usage:

let dateString = DateFormatter.sharedDateFormatter.string(from: Date())

I always use this code while converting Date to String . (Swift 3)

extension Date
{
    func toString( dateFormat format  : String ) -> String
    {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: self)
    }

}

and call like this . .

let today = Date()
today.toString(dateFormat: "dd-MM")

DateFormatter has some factory date styles for those too lazy to tinker with formatting strings. If you don't need a custom style, here's another option:

extension Date {  
  func asString(style: DateFormatter.Style) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = style
    return dateFormatter.string(from: self)
  }
}

This gives you the following styles:

short, medium, long, full

Example usage:

let myDate = Date()
myDate.asString(style: .full)   // Wednesday, January 10, 2018
myDate.asString(style: .long)   // January 10, 2018
myDate.asString(style: .medium) // Jan 10, 2018
myDate.asString(style: .short)  // 1/10/18

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to swift3

Xcode 9 Swift Language Version (SWIFT_VERSION) Convert NSDate to String in iOS Swift Waiting until the task finishes Type of expression is ambiguous without more context Swift Removing object from array in Swift 3 Generate your own Error code in swift 3 Swift 3: Display Image from URL add Shadow on UIView using swift 3 how to open an URL in Swift3 Correctly Parsing JSON in Swift 3

Examples related to nsdateformatter

Convert NSDate to String in iOS Swift Convert string to date in Swift Date Format in Swift How to convert string to date to string in Swift iOS? Xcode swift am/pm time to 24 hour format Swift - iOS - Dates and times in different format Get current NSDate in timestamp format Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds