String can't be parsed into Date "Swift" - ios

I'm trying to parse the following String input "2020-04-05 19:02:02" into Date, which I'm using the following code to do that:
static func getDateFromString(_ dateStr: String) -> Date? {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "yyyy-MM-dd H:mm:ss"
dateFormater.timeZone = TimeZone(identifier: "UTC")
return dateFormater.date(from: dateStr)
}
The problem is that not working, it returns nil
Any suggestion? Thank you

Here you go, this works fine:
In dateString pass data in string format and for dateFormat pass format you want and to choose format use NSDateFormatter:
let expiryDateString = "2020-04-05 19:02:02"
let dateformat = "yyyy-MM-dd HH:mm:ss"
let expireDate = DateHelper.getDateFrom(expireDateString, dateformat)
static func getDateFrom(dateString: String,dateFormat: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatter.timeZone = .current
guard let date = dateFormatter.date(from: dateString) else {return nil}
return date
}

Related

Date from String using DateFormatter returning nil

I've a String like yyyy-MM-dd and I want create a Date with this.
static func dateFromStringWithBarra(date : String) -> String {
print("DATE: \(date)")
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date_from_format = dateFormatter.date(from: date)
print("date_from_format: \(date_from_format)")
dateFormatter.dateFormat = "dd/MM/yyyy"
print("date_from_format: \(date_from_format)")
return dateFormatter.string(from: date_from_format!) // <- nil
}
OUTPUT:
DATE: 2018-11-04
date_from_format: nil
date_from_format: nil
I had the same problem, mine was solved by some reason just by adding the locale to the DateFormatter:
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "es_MX_POSIX")
Hope it helps.
A few things about that code:
1) Not sure why you use two different date formats
2) You should avoid if possible to use force unwrapping, in this case probably guard would be a good choice.
Meaning that the code should look more like this:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
guard let date_from_format = dateFormatter.date(from: date) else {
return ""
}
return dateFormatter.string(from: date_from_format)

How to convert string to NSDate in Swift?

How can I convert a string like 05/18/2017 this to NSDate?
I am trying to convert this string to NSDate so that I can extract the day as 18 and month as 05 and year as 2017. How can I convert this or can extract those values from strings.
func toDate(dateString : String, dateFormat : String = "yyyy-MM-dd'T'HH:mm:ssX")-> NSDate!{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let convertedDate = dateFormatter.dateFromString(dateString)
return convertedDate
}
Now in code below selectedValue is 05/18/2017 but NSDateFromString always shows nil value:
let nsdateFromString = String.toDate(selectedValue)
What can I do in this case?
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")
**in SWIFT 3.0,**
let strDate = "12/21/2017"
let datefrmter = DateFormatter()
datefrmter.dateFormat = "mm/dd/yyyy"
let date = datefrmter.date(from: strDate)
print(date)
func convertSToD(date : String)-> Date?{
if date != "NA"{
let interval = Double(date)
let dateFormat = Date(timeIntervalSince1970: interval!)
return dateFormat
}
return nil
}
Try this :-
func toDate(dateString : String, dateFormat : String = "MM/dd/yyyy")-> NSDate!{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let convertedDate = dateFormatter.dateFromString(dateString)
return convertedDate
}
Convert Current date and time
let formatter1 = DateFormatter()
let date1 = Date.init()
formatter1.dateFormat = "dd-MMM-yyyy hh:mm a"
let days = formatter1.string(from: date1 as Date)
print(days)
//in Swift 3.0 converting string to NSDate with its format
let dateString = self.scoring_date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
dateFormatter.locale = Locale.init(identifier: "en_GB")
self.dateObj = dateFormatter.date(from: dateString! as String )!
dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: self.dateObj))")
//converting NSDate to String
let today = Date()
today.toString(dateFormat: "dd-MM")

Convert NSDate to String in iOS Swift [duplicate]

This question already has answers here:
Convert NSDate to NSString
(19 answers)
Closed 5 years ago.
I am trying to convert a NSDate to a String and then Change Format. But when I pass NSDate to String it is producing whitespace.
let formatter = DateFormatter()
let myString = (String(describing: date))
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
print(yourDate)
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
I always use this code while converting Date to String . (Swift 3)
extension Date
{
func toString( dateFormat format : String ) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}
and call like this . .
let today = Date()
today.toString(dateFormat: "dd-MM")
DateFormatter has some factory date styles for those too lazy to tinker with formatting strings. If you don't need a custom style, here's another option:
extension Date {
func asString(style: DateFormatter.Style) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = style
return dateFormatter.string(from: self)
}
}
This gives you the following styles:
short, medium, long, full
Example usage:
let myDate = Date()
myDate.asString(style: .full) // Wednesday, January 10, 2018
myDate.asString(style: .long) // January 10, 2018
myDate.asString(style: .medium) // Jan 10, 2018
myDate.asString(style: .short) // 1/10/18
Your updated code.update it.
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date as Date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
print(yourDate!)
Something to keep in mind when creating formatters is to try to reuse the same instance if you can, as formatters are fairly computationally expensive to create. The following is a pattern I frequently use for apps where I can share the same formatter app-wide, adapted from NSHipster.
extension DateFormatter {
static var sharedDateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
// Add your formatter configuration here
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter
}()
}
Usage:
let dateString = DateFormatter.sharedDateFormatter.string(from: Date())
After allocating DateFormatter you need to give the formatted string
then you can convert as string like this way
var date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
let updatedString = formatter.string(from: yourDate!)
print(updatedString)
OutPut
01-Mar-2017
You can use this extension:
extension Date {
func toString(withFormat format: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = format
let myString = formatter.string(from: self)
let yourDate = formatter.date(from: myString)
formatter.dateFormat = format
return formatter.string(from: yourDate!)
}
}
And use it in your view controller like this (replace <"yyyy"> with your format):
yourString = yourDate.toString(withFormat: "yyyy")

Swift 3 changing date format

I want to get my Date in DD.MM.YYYY HH:mm:ss as a String.
I use the following extension:
extension Date {
var localTime: String {
return description(with: Locale.current)
}
}
and the following code when my datePicker changes:
#IBAction func datePickerChanged(_ sender: UIDatePicker) {
dateLabel.text = datePicker.date.localTime
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy hh:mm"
let TestDateTime = formatter.date(from: datePicker.date.localTime)
}
What am I doing wrong?
Your code is completely wrong. Just do the following:
#IBAction func datePickerChanged(_ sender: UIDatePicker) {
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy HH:mm"
dateLabel.text = formatter.string(from: sender.date)
}
This will convert the date picker's chosen date to a string in the format dd.MM.yyyy HH:mm in local time.
Never use the description method to convert any object to a user presented value.
Just used the function in your code(swift 4.2).
public func convertDateFormatter(date: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"//this your string date format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
dateFormatter.locale = Locale(identifier: "your_loc_id")
let convertedDate = dateFormatter.date(from: date)
guard dateFormatter.date(from: date) != nil else {
assert(false, "no date from string")
return ""
}
dateFormatter.dateFormat = "HH:mm a"///this is what you want to convert format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let timeStamp = dateFormatter.string(from: convertedDate!)
print(timeStamp)
return timeStamp
}
Thanks

How can I convert string date to NSDate?

I want to convert "2014-07-15 06:55:14.198000+00:00" this string date to NSDate in Swift.
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
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
Edit:
Alternative date time format reference
https://unicode-org.github.io/icu/userguide/format_parse/datetime/
Swift 4
import Foundation
let dateString = "2014-07-15" // change to your date format
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: dateString)
println(date)
Swift 3
import Foundation
var dateString = "2014-07-15" // change to your date format
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var date = dateFormatter.dateFromString(dateString)
println(date)
I can do it with this code.
func convertDateFormatter(date: String) -> String
{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date = dateFormatter.dateFromString(date)
dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"///this is what you want to convert format
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let timeStamp = dateFormatter.stringFromDate(date!)
return timeStamp
}
Updated for Swift 3.
func convertDateFormatter(date: String) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let date = dateFormatter.date(from: date)
dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"///this is what you want to convert format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let timeStamp = dateFormatter.string(from: date!)
return timeStamp
}
Details
Swift 4, Xcode 9.2
Swift 5, Xcode 10.2 (10E125)
Solution
import Foundation
extension DateFormatter {
convenience init (format: String) {
self.init()
dateFormat = format
locale = Locale.current
}
}
extension String {
func toDate (dateFormatter: DateFormatter) -> Date? {
return dateFormatter.date(from: self)
}
func toDateString (dateFormatter: DateFormatter, outputFormat: String) -> String? {
guard let date = toDate(dateFormatter: dateFormatter) else { return nil }
return DateFormatter(format: outputFormat).string(from: date)
}
}
extension Date {
func toString (dateFormatter: DateFormatter) -> String? {
return dateFormatter.string(from: self)
}
}
Usage
var dateString = "14.01.2017T14:54:00"
let dateFormatter = DateFormatter(format: "dd.MM.yyyy'T'HH:mm:ss")
let date = Date()
print("original String with date: \(dateString)")
print("date String() to Date(): \(dateString.toDate(dateFormatter: dateFormatter)!)")
print("date String() to formated date String(): \(dateString.toDateString(dateFormatter: dateFormatter, outputFormat: "dd MMMM")!)")
let dateFormatter2 = DateFormatter(format: "dd MMM HH:mm")
print("format Date(): \(date.toString(dateFormatter: dateFormatter2)!)")
Result
More information
About date format
If you're going to need to parse the string into a date often, you may want to move the functionality into an extension. I created a sharedCode.swift file and put my extensions there:
extension String
{
func toDateTime() -> NSDate
{
//Create Date Formatter
let dateFormatter = NSDateFormatter()
//Specify Format of String to Parse
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx"
//Parse into NSDate
let dateFromString : NSDate = dateFormatter.dateFromString(self)!
//Return Parsed Date
return dateFromString
}
}
Then if you want to convert your string into a NSDate you can just write something like:
var myDate = myDateString.toDateTime()
For Swift 3
func stringToDate(_ str: String)->Date{
let formatter = DateFormatter()
formatter.dateFormat="yyyy-MM-dd hh:mm:ss Z"
return formatter.date(from: str)!
}
func dateToString(_ str: Date)->String{
var dateFormatter = DateFormatter()
dateFormatter.timeStyle=DateFormatter.Style.short
return dateFormatter.string(from: str)
}
The code fragments on this QA page are "upside down"...
The first thing Apple mentions is that you cache your formatter...
Link to Apple doco stating exactly how to do this:
Cache Formatters for Efficiency
Creating a date formatter is not a cheap operation. ...cache a single instance...
Use a global...
let df : DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
Then simply use that formatter anywhere...
let s = df.string(from: someDate)
or
let d = df.date(from: someString)
Or use any of the other many, many convenient methods on DateFormatter.
It is that simple.
(If you write an extension on String, your code is completely "upside down" - you can't use any dateFormatter calls!)
Note that usually you will have a few of those globals .. such as "formatForClient" "formatForPubNub" "formatForDisplayOnInvoiceScreen" .. etc.
Swift support extensions, with extension you can add a new functionality to an existing class, structure, enumeration, or protocol type.
You can add a new init function to NSDate object by extenging the object using the extension keyword.
extension NSDate
{
convenience
init(dateString:String) {
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "yyyyMMdd"
dateStringFormatter.locale = NSLocale(localeIdentifier: "fr_CH_POSIX")
let d = dateStringFormatter.dateFromString(dateString)!
self.init(timeInterval:0, sinceDate:d)
}
}
Now you can init a NSDate object using:
let myDateObject = NSDate(dateString:"2010-12-15 06:00:00")
Since Swift 3, many of the NS prefixes have been dropped.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
/* date format string rules
* http://userguide.icu-project.org/formatparse/datetime
*/
let date = dateFormatter.date(from: dateString)
Swift 3,4:
2 useful conversions:
string(from: Date) // to convert from Date to a String
date(from: String) // to convert from String to Date
Usage:
1.
let date = Date() //gives today's date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy"
let todaysDateInUKFormat = dateFormatter.string(from: date)
2.
let someDateInString = "23.06.2017"
var getDateFromString = dateFormatter.date(from: someDateInString)
FOR SWIFT 3.1
func convertDateStringToDate(longDate: String) -> String{
/* INPUT: longDate = "2017-01-27T05:00:00.000Z"
* OUTPUT: "1/26/17"
* date_format_you_want_in_string from
* http://userguide.icu-project.org/formatparse/datetime
*/
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.date(from: longDate)
if date != nil {
let formatter = DateFormatter()
formatter.dateStyle = .short
let dateShort = formatter.string(from: date!)
return dateShort
} else {
return longDate
}
}
NOTE: THIS WILL RETURN THE ORIGINAL STRING IF ERROR
To add String within Date Format in Swift, I did this
var dataFormatter:NSDateFormatter = NSDateFormatter()
dataFormatter.dateFormat = "dd-MMMM 'at' HH:mm a"
cell.timeStamplbl.text = dataFormatter.stringFromDate(object.createdAt)
This work for me..
import Foundation
import UIKit
//dateString = "01/07/2017"
private func parseDate(_ dateStr: String) -> String {
let simpleDateFormat = DateFormatter()
simpleDateFormat.dateFormat = "dd/MM/yyyy" //format our date String
let dateFormat = DateFormatter()
dateFormat.dateFormat = "dd 'de' MMMM 'de' yyyy" //format return
let date = simpleDateFormat.date(from: dateStr)
return dateFormat.string(from: date!)
}
You can try this swift code
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"//same as strDate date formator
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00")//Must used if you get one day less in conversion
let convertedDateObject = dateFormatter.date(from: strDate)
Below are some string to date format converting options can be usedin swift iOS.
Thursday, Dec 27, 2018 format= EEEE, MMM d, yyyy
12/27/2018 format= MM/dd/yyyy
12-27-2018 09:59 format= MM-dd-yyyy HH:mm
Dec 27, 9:59 AM format= MMM d, h:mm a
December 2018 format= MMMM yyyy
Dec 27, 2018 format= MMM d, yyyy
Thu, 27 Dec 2018 09:59:19 +0000 format= E, d MMM yyyy HH:mm:ss Z
2018-12-27T09:59:19+0000 format= yyyy-MM-dd'T'HH:mm:ssZ
27.12.18 format= dd.MM.yy
09:59:19.815 format= HH:mm:ss.SSS
SWIFT 5, Xcode 11.0
Pass your (date in string) in "dateString" and in "dateFormat" pass format you want. To choose format, use NDateFormatter website.
func getDateFrom(dateString: String, dateFormat: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatter.locale = Locale(identifier: "en_US")
guard let date = dateFormatter.date(from: dateString) else {return nil}
return date
}
Swift: iOS
if we have string, convert it to NSDate,
var dataString = profileValue["dob"] as String
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
// convert string into date
let dateValue:NSDate? = dateFormatter.dateFromString(dataString)
if you have and date picker parse date like this
// to avoid any nil value
if let isDate = dateValue {
self.datePicker.date = isDate
}
import Foundation
let now : String = "2014-07-16 03:03:34 PDT"
var date : NSDate
var dateFormatter : NSDateFormatter
date = dateFormatter.dateFromString(now)
date // $R6: __NSDate = 2014-07-16 03:03:34 PDT
https://developer.apple.com/library/prerelease/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/index.html#//apple_ref/doc/uid/20000447-SW32

Resources