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)!
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
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 convert string to date to string in Swift iOS?
First, you need to convert your string to NSDate with its format. Then, you change the dateFormatter
to your simple format and convert it back to a String.
Swift 3
let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateObj = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: dateObj!))")
The printed result is: Dateobj: 10-22-2015
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
How to convert string to NSDate in Swift?
The default dateFormat
value of your function toDate
not matching the selectedValue
's date format, so you need to pass dateFormat
argument also with your method call with value MM/dd/yyyy
.
let nsdateFromString = String.toDate(dateString: selectedValue, dateFormat: "MM/dd/yyyy")
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 String to NSDate with Swift 2
The "T" in the format string needs to be single quoted so it will not be consider a symbol:
Swift 3.0
let strDate = "2015-11-01T00:00:00Z"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:strDate)
print("date: \(date!)")
Output:
date: 2015-11-01 00:00:00 +0000
Swift 2.x
let strDate = "2015-11-01T00:00:00Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.dateFromString(strDate)
print("date: \(date!)")
Output:
date: 2015-11-01 00:00:00 +0000
See: Date Field SymbolTable.
This includes the need to enclose ASCII letters in single quotes if they are intended to represent literal text.
Related Topics
Take Screenshot of Host App Using iOS Share/Action Extensions
How to Get Core Data Entity by It's Objectid
Swift ? Must Be Followed by a Call, Member Lookup, or Subscript
Table View Cellforrowatindexpath Warning
What's Wrong with My #If Target_Os_Simulator Code for Realm Path Definition
Problem with Gesture in Xcode 12 and iOS 14
"Message from Debugger: Unable to Attach" When Running Tests on Osx App
Swift - Kvo - Change.Newvalue and Change.Oldvalue Are Nil
Dyld: Library Not Loaded, App Requires Afnetworking 2.0.0 But Provides Version 1.0.0
What's the Rationale of Swift's Size Methods Taking 'Int'S
Ios-Charts Set Maximum Visible X Axis Values
How to Get Title from Wkinterfacebutton
Swift: Oslog/Os_Log Not Showing Up in Console App
Swiftui Pick a Value from a List with Ontap Gesture
How to Call a Method on a Uiview from Outside the Uiviewrepresentable in Swiftui
Unit Testing Wknavigationdelegate Functions
New' Is Unavailable: You Cannot Directly Instantiate an Stpissuingcardpin