how to convert a date string into a NSDate type swift
It is way easier for both you and the user if you let the user choose a date from a UIDatePicker
. This has a lot of advantages:
- The user don't have to type in three text fields
- You can get the selected date via the
date
property. You don't need all these formatters and stuff - You can set a maximum date that the user can select via the
maximumDate
property. This way you don't have to check if it is in the future manually. Just setmaximumDate
to now. - The date picker will use different formats depending on the user's locale. You don't need to worry about it at all.
Just remember to set the datePickerMode
to .date
!
As for the conversion to NSDate
, you can do this easily by this expression:
datePicker.date as NSDate
If you insist on using three text fields, you can do this:
dateFormatter.date(from: dateString) as NSDate? // note that this produces an optional
Convert string to date in Swift
Convert the ISO8601 string to date
let isoDate = "2016-04-14T10:44:00+0000"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:isoDate)!Get the date components for year, month, day and hour from the date
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)Finally create a new
Date
object and strip minutes and secondslet finalDate = calendar.date(from:components)
Consider also the convenience formatter ISO8601DateFormatter
introduced in iOS 10 / macOS 10.12:
let isoDate = "2016-04-14T10:44:00+0000"
let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from:isoDate)!
How can I convert string date to NSDate?
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 (Swift 4 included)
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
How to extract the date from Swift String as NSDate?
You have wrong Parameter passed
var dateString: String = "2017-05-04 13:46:36.0"
var dateFormatter1 = DateFormatter()
dateFormatter1.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
var yourDate: Date? = dateFormatter1.date(from: dateString)
dateFormatter1.dateFormat = "yyyy-MM-dd"
Rule of Date formatter is you must set date format same like your string while you are getting date from string , if mismatch then you will get null
Swift 2
var dateString: String = "2017-05-04 13:46:36.0"
var dateFormatter1: NSDateFormatter = NSDateFormatter()
dateFormatter1.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
var yourDate: NSDate = dateFormatter1.dateFromString(dateString)
dateFormatter1.dateFormat = "yyyy-MM-dd"
print("\(dateFormatter1.stringFromDate(yourDate))")
Convert date string to NSDate
Your date format and your time string should be same. In your case it should be like,
let formatterJsonDate = DateFormatter()
formatterJsonDate.dateFormat = "yyy-MM-dd HH:mm:ss"
print(formatterJsonDate.date(from: "2016-10-08 00:20:00"))
Or change dateformatter like,
"yyyy-MM-dd HH:mm:ss.SSSSSS"
And hh
should be capital for 24 - hour format!!!! like HH
!
Converting a string to NSDate in Swift
See this answer :
let myDateString = "2016-05-06T14:07:23.430Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-dd-MM'T'HH:mm:ss.SSS'Z"
let dateFromString = dateFormatter.dateFromString(myDateString)
let dateFormatter1 = NSDateFormatter()
dateFormatter1.dateFormat = "MM-dd-yy H:mm"
let getDate = dateFormatter1.stringFromDate(dateFromString!)
print(getDate)
Your OUTPUT :
Convert NSDate to Date
result.date
is an optional NSDate
, so you can bridge it
to an optional Date
:
result.date as Date?
Then use optional binding to safely unwrap it. In your case that
could be
guard let date = result.date as Date? else {
// date is nil, ignore this entry:
continue
}
You might also want to replace
let commnt = String(describing: result.commnt)
with
guard let commnt = result.commnt else {
// commnt is nil, ignore this entry:
continue
}
otherwise you'll get comment strings like Optional(My comment)
.
(Rule of thumb: String(describing: ...)
is almost never what you
want, even if the compiler suggests it to make the code compile.)
Converting NSString to NSDate (and back again)
Swift 4 and later
Updated: 2018
String to Date
var dateString = "02-03-2017"
var dateFormatter = DateFormatter()
// This is important - we set our input date format to match our input string
// if the format doesn't match you'll get nil from your string, so be careful
dateFormatter.dateFormat = "dd-MM-yyyy"
//`date(from:)` returns an optional so make sure you unwrap when using.
var dateFromString: Date? = dateFormatter.date(from: dateString)
Date to String
var formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
guard let unwrappedDate = dateFromString else { return }
//Using the dateFromString variable from before.
let stringDate: String = formatter.string(from: dateFromString)
Swift 3
Updated: 20th July 2017
String to NSDate
var dateString = "02-03-2017"
var dateFormatter = DateFormatter()
// This is important - we set our input date format to match our input string
// if the format doesn't match you'll get nil from your string, so be careful
dateFormatter.dateFormat = "dd-MM-yyyy"
var dateFromString = dateFormatter.date(from: dateString)
NSDate to String
var formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
let stringDate: String = formatter.string(from: dateFromString)
Swift
Updated: 22nd October 2015
String to NSDate
var dateString = "01-02-2010"
var dateFormatter = NSDateFormatter()
// this is imporant - we set our input date format to match our input string
dateFormatter.dateFormat = "dd-MM-yyyy"
// voila!
var dateFromString = dateFormatter.dateFromString(dateString)
NSDate to String
var formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
let stringDate: String = formatter.stringFromDate(NSDate())
println(stringDate)
Objective-C
NSString to NSDate
NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [dateFormatter dateFromString:dateString];
NSDate convert to NSString:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", stringDate);
Convert NSDate to String in iOS Swift
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 myStringDate = formatter.string(from: yourDate!)
print(myStringDate)
you get the output as
Related Topics
Selector to Get Indexpath Uicollectionview Swift 3.0
How to Prevent iOS 13 Dark Mode from Breaking Emails
Getting Back a Date from a String
Disable Autolayout Constraint Error Messages in Debug Console Output in Xcode
Make Custom Button on Tab Bar Rounded
Swift Numerics and Cgfloat (Cgpoint, Cgrect, etc.)
Startupdatelocations in Background, Didupdatingtolocation Only Called 10-20 Times
Detect "Allow Notifications" Is On/Off for iOS8
Swiftui: Navigationdestinationlink Deprecated
How to Create Otp Verification Screen and Detect Delete Backward on Multiple Uitextfield Is Swift
Input Field iOS Safari Bug - Can't Type in Any Text
How to Disable the Network in iOS Simulator
Notificationcenter Issue on Swift 3
Build Not Visible in Itunes Connect
Presenting a View Controller Modally from an Action Sheet's Delegate in iOS8 - iOS11