2

I have a Date object, like so:

 2017-06-08 08:36:16 +0000

I need to convert this to a string, in this form:

"2017-06-08T08:36:16Z"

The REST api I am posting to only accepts dates as strings.

Most info I find online is about converting dates to human readable formats. If possible, I could probably even just "stringify" my date object, however trying to cast it as such obviously fails. There are tons of "convert date to string" questions out there, but haven't ran across any like this yet.

Any idea how to do this?

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
jjjjjjjj
  • 4,203
  • 11
  • 53
  • 72
  • 2
    How is `"2017-06-08T08:36:16Z"` a "non human-readable" string? – What prevents you from using a `DateFormatter`? – Martin R Jun 08 '17 at 08:56
  • probably just reverse of [this question](https://stackoverflow.com/questions/41907419/ios-swift-3-convert-yyyy-mm-ddthhmmssz-format-string-to-date-object?rq=1) – Tj3n Jun 08 '17 at 08:57
  • @MartinR sorry it was confusing. I meant it as in, most questions like this want a string output like "June 7, 2017" (something you may output to a user), where as you would rarely (if ever) output "2017-06-08T08:36:16Z" to a user. – jjjjjjjj Jun 08 '17 at 09:02
  • Have a look at this page: http://nsdateformatter.com It is a good reference when "designing" your `dateFormat` strings :) – pbodsk Jun 08 '17 at 09:13

3 Answers3

3

All you have to do is changing the date format (DateFormatter) to the desired one.

Note that the format of your given date (2017-06-08 08:36:16 +0000) is:

yyyy-MM-dd HH:mm:ss Z

For instance, consider that the given date value is today, you could read it -as a string- like this:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"

let givenDate = Date()
let stringGivenDate = dateFormatter.string(from: givenDate) // 2017-06-08 12:10:23 +0300

thus, changing the date format to:

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:SS'Z'"
let stringGivenDateWithDesiredFormat = dateFormatter.string(from: givenDate) // 2017-06-08T12:11:75Z

As per the code snippet above, your given desired format (2017-06-08T08:36:16Z) is:

yyyy-MM-dd'T'HH:mm:SS'Z'

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
2

Try this

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:SS'Z'"
let dateDate =  NSDate()
let stringDate = dateFormatter.string(from: date as Date)

Where date is your Date object in 2017-06-08 08:36:16 +0000 format

Aravind A R
  • 2,674
  • 1
  • 15
  • 25
2

Following two formats will work for you. yyyy-MM-dd HH:mm:ss Z and yyyy-MM-dd'T'HH:mm:ss'Z'

let input = "2017-06-08 08:36:16 +0000"
let dateFormater = DateFormatter.init()
dateFormater.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
if let date = dateFormater.date(from: input) {
    dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
    let output = dateFormater.string(from: date)
    print(output)
}
Bilal
  • 18,478
  • 8
  • 57
  • 72