How can I convert a date format to another date format in Swift?

user3766930

I currently have a code:

let now = NSDate()
let result: NSDate
result = Cal.iso8601.dateByAddingUnit(.Year, value: -5, toDate: now, options: [])!
return Cal.iso8601.startOfDayForDate(result)

that generates a date in the format:

2016-09-15 22:00:00 +0000

and I want to convert it to this date format:

2016-09-16T13:49:23.221Z

how can I do it in Swift?

Rashwan L

DateFormatter requires a lot of resources so use this extension so that you only create one instance of the formatter.

struct Formatter {
    static let instance = NSDateFormatter(dateFormat: "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
}
extension NSDateFormatter {
    convenience init(dateFormat: String) {
        self.init()
        self.dateFormat = dateFormat
    }
}

Then just call it with:

// dateTime = the date that you want to format
let date = Formatter.instance.dateFromString(dateTime)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I convert a date into another format with moment.js?

How to convert date of string format to another string format in swift(ios)

How can I convert a date format in SQL?

How can I convert this date-format in a format accepted by lubridate?

How can I convert "/Date(1399739515000)/" into date format in JavaScript?

Convert Date to another format

How can I get georgian date format in a machine which date format set to another format?

How do I take string date input and convert it into another format?

How can I convert get date to format of yyyymmdd?

How can I convert the Date format for column in sqlite table?

How can I convert a custom `dayHour` string variable to date format?

How can I convert this query result to date format (SQL Server)

JavaScript How Can I convert this innerText to a valid date format?

How can I convert a date in YYYYMMDDHHMMSS format to epoch or unix time?

How can I convert a specific string format to date or datetime in Spark?

How can I export to sqlite (or another format) and retain the date datatype?

Can't Convert Date Format Into Display Date In Swift

How to convert one date format to another format using angular JS?

Convert timestamp into another date format

How do I convert the date from one format to another date object in another format without using any deprecated classes?

How do I convert a factor into date format?

How do I convert date to format "ddmmyyyy"

How do I convert another language date format to English language format (Y-m-d)?

convert date in one format to another format

Can I convert a date in the format YYYYMMDDHHMM using date?

How to convert the each date components to particular date format in swift 2

Convert date string to another date string format

Convert Date with milliseconds to another date format

How can I convert an German date format with two digits in year to UTC-format?