• Home
  • About
  • Our Apps
  • Learn
  • Contact
Login

Register

Login
Seemu Apps Seemu Apps
  • Home
  • About
  • Our Apps
  • Learn
  • Contact

Converting a NSDate to a String and String to a NSDate

Home ios Converting a NSDate to a String and String to a NSDate

Converting a NSDate to a String and String to a NSDate

Mar 30, 2016 | Posted by Andrew | ios, swift, tutorial, xcode |

Converting a NSDate to a String and back again is easy with a few lines of code.

NSDate to String

let date = NSDate() // Get Todays Date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
let stringDate: String = dateFormatter.string(from: date as Date)
print(stringDate)

String to NSDate

var dateString = "30-03-2016"
var dateFormatter = DateFormatter()
// Our date format needs to match our input string format
dateFormatter.dateFormat = "dd-MM-yyyy"

// The below line is optional, as NSDate uses the GMT +0 timezone by default
// The output day may be slightly off due your timezone
// This will align it with the NSDate timezone default GMT + 0
// Keep in mind users of your app all have different timezones and this will make the date use GMT+0 timezone instead of a users local one

//dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT+0:00") as TimeZone!

var dateFromString = dateFormatter.date(from: dateString)
print(dateString)

Easy peasy – just when converting a String to NSDate remmber the dateFormatter must match the same format as your String! You can find a cheat sheet on the date formatter dateFormat codes here.

 

Tags: convertdatedateformatterdatestringNSDatestring
1
Share

About Andrew

Andrew is a 24 year old from Sydney. He loves developing iOS apps and has done so for two years.

You also might be interested in

Get nth character of a String & get a Substring from a String

Apr 18, 2016

To get n character of a String in Swift you[...]

Swift Extensions – speed up app development

May 24, 2017

Swift Extensions are quite a powerful feature and Swift and[...]

Split String into Array by Words

Apr 5, 2016

Splitting a string into an array based on the word[...]

Welcome

Hi I am Andrew and welcome to Seemu Apps! Have a look around, we provide tutorials for primarily iOS apps.
Bluehost website hosting discount

Seemu’s Studio Setup

Blue Yeti Microphone
Rode Stand
Spider Shock Mount
Mac Keyboard Cover
Screenflow - recording software

Contact Us

We're currently offline. Send us an email and we'll get back to you, asap.

Send Message

Footer

:)

© 2026 · Your Website. Theme by HB-Themes.

  • Home
  • About
  • Our Apps
  • Learn
  • Contact
Prev Next