swift 5 - String to Date conversion results in nil [duplicate] - ios

This question already has an answer here:
DateFormatter doesn't return date for "HH:mm:ss"
(1 answer)
Closed 2 years ago.
Has something changed in Swift 5.x? Not sure what I'm doing wrong here.
extension String {
var dateValue: Date? {
let dateAsString = "13:15"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let date = dateFormatter.date(from: dateAsString) //date is being nil here
let Date24 = dateFormatter.string(from: date!)
print("24 hour formatted Date:",Date24)
return date
}
}

Change your code to :
let dateAsString = "13:15"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+00:00")//Add this
let date = dateFormatter.date(from: dateAsString)
print(date!)
My result is :
2000-01-01 13:15:00 +0000
Hope it helps...

Related

Getting wrong time from dateformatter [duplicate]

This question already has answers here:
Dateformatter gives wrong time on conversation [duplicate]
(4 answers)
Closed 5 years ago.
I'm converting date fields from a XML file and these dates are stored in "yyyyMMddHHmmss" format. When I use date function of DateFormmater, I'm not getting the correct time. So for dateString "20150909093700", it returns "2015-09-09 13:37:00 UTC" instead of "2015-09-09 09:37:00". I'm doing this conversion before storing inside Core Data NSDate fields.
This is my code :
static func stringToDate(DateString dateString: String) -> NSDate? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMddHHmmss"
dateFormatter.locale = Locale.init(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(abbreviation: "EST")
if let date = dateFormatter.date(from: dateString) {
return date as NSDate?
}
return nil
}
#user30646 -- see if this makes sense. Using your exact function:
func stringToDate(DateString dateString: String) -> NSDate? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMddHHmmss"
dateFormatter.locale = Locale.init(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(abbreviation: "EST")
if let date = dateFormatter.date(from: dateString) {
return date as NSDate?
}
return nil
}
let dateString = "20150909093700"
let returnedDate = stringToDate(DateString: dateString)
print("Date without formatting or Time Zone: [", returnedDate ?? "return was nil", "]")
let dFormatter = DateFormatter()
dFormatter.timeZone = TimeZone(abbreviation: "EST")
dFormatter.dateStyle = .full
dFormatter.timeStyle = .full
print("Result with formatting and Time Zone: [", dFormatter.string(from: returnedDate as! Date), "]")
You are getting the "correct time" ... you just think you're not because you're looking at the wrong string representation of that date/time.

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")

Convert string to DATE type in swift 3 [duplicate]

This question already has answers here:
Dateformatter to get Date From String
(4 answers)
Closed 4 years ago.
I have this structure:
struct message {
var id: String = "0"
var text: String = ""
var date: Date!
var status: String = ""
}
I have to load this structure from dbase, that it export in String format also date.
So I write this code to convert String to Date type:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone!
let dataDate = dateFormatter.date(from: elemMessage["date"] as! String)!
And I load it in structure:
message(id: elemMessage["id"] as! String, text: elemMessage["text"] as! String, date: dataDate as! Date, status: elemMessage["status"] as! String)
But I have this warning: "Cast from Date to unrelated type Date always fails"
So if I run app it will fails.
How Can I fix this, the date var in structure have to be Date type.
Thank you.
You can convert String Date into Date/NSDate like below code: -
Swift 3.2 & Swift 4.2
String to Date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy" //Your date format
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00") //Current time zone
//according to date format your date string
guard let date = dateFormatter.date(from: "01-01-2017") else {
fatalError()
}
print(date) //Convert String to Date
Date to String
dateFormatter.dateFormat = "MMM d, yyyy" //Your New Date format as per requirement change it own
let newDate = dateFormatter.string(from: date) //pass Date here
print(newDate) //New formatted Date string
Output: -
2017-01-11 00:07:00 +0000
Jan 11, 2017
Swift 4 ISO
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone.autoupdatingCurrent
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
func getDateFromString(dateStr: String) -> (date: Date?,conversion: Bool)
{
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
let dateComponentArray = dateStr.components(separatedBy: "/")
if dateComponentArray.count == 3 {
var components = DateComponents()
components.year = Int(dateComponentArray[2])
components.month = Int(dateComponentArray[1])
components.day = Int(dateComponentArray[0])
components.timeZone = TimeZone(abbreviation: "GMT+0:00")
guard let date = calendar.date(from: components) else {
return (nil , false)
}
return (date,true)
} else {
return (nil,false)
}
}
//Input: "23/02/2017"
//Output: (2017-02-23 18:30:00 +0000, true)

How to convert date format from dd/MM/YYYY to YYYY-MM-dd in swift [duplicate]

This question already has answers here:
Format a date from a string
(5 answers)
Closed 6 years ago.
I tired to covert from 21/07/2016 to 2016-07-21 but got this date 2015-12-20
Here is the Code that i have try
let inputFormatter = NSDateFormatter()
inputFormatter.dateFormat = "MM/dd/YYYY"
let outputFormatter = NSDateFormatter()
outputFormatter.dateFormat = "YYYY-MM-dd"
let showDate = inputFormatter.dateFromString("07/21/2016")
let resultString = outputFormatter.stringFromDate(showDate!)
print(resultString)
How to convert?
Thank you
First changes your year formatter with yyyy and instead of using two NSDateFormatter use just one like this
let inputFormatter = NSDateFormatter()
inputFormatter.dateFormat = "MM/dd/yyyy"
let showDate = inputFormatter.dateFromString("07/21/2016")
inputFormatter.dateFormat = "yyyy-MM-dd"
let resultString = inputFormatter.stringFromDate(showDate!)
print(resultString)
For Swift3 and later
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let date = dateFormatter.date(from: date)
dateFormatter.dateFormat = "yyyy-MM-dd"
let resultString = dateFormatter.string(from: date!)
print(resultString)
You can define a function like the one below:
// input string should always be in format "21/07/2016" ("dd/MM/yyyy")
func formattedDateFromString(dateString: String, withFormat format: String) -> String? {
let inputFormatter = NSDateFormatter()
inputFormatter.dateFormat = "dd/MM/yyyy"
if let date = inputFormatter.dateFromString(dateString) {
let outputFormatter = NSDateFormatter()
outputFormatter.dateFormat = format
return outputFormatter.stringFromDate(date)
}
return nil
}
You can use the above to pass an output format for your date string. Input format will always be dd/MM/yyyy. Then you use it as follows:
let stringA = formattedDateFromString("21/07/2016", withFormat: "yyyy-MM-dd")
let stringB = formattedDateFromString("21/07/2016", withFormat: "MMM dd, yyyy")
NSLog("stringA: \(stringA)") // 2016-07-21
NSLog("stringB: \(stringB)") // Jul 21, 2016

How to convert string to date to string in Swift iOS? [duplicate]

This question already has answers here:
Converting NSString to NSDate (and back again)
(17 answers)
Closed 7 years ago.
Am learning swift and am struck in converting the date String to NSDate to string. Am getting the date string in this format "Thu, 22 Oct 2015 07:45:17 +0000". I need to show the date in the MM-dd-yyyy format. I tried the following code but, it returns "null".
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
let dateObj = dateFormatter.dateFromString(dateString!)
print("Dateobj: \(dateObj)")
Can anyone please help where am going wrong? Looking forward the help. Thanks in advance.
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
//String to Date Convert
var dateString = "2014-01-12"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)
println(s)
//CONVERT FROM NSDate to String
let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)
Swift 2 and below
let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)
And in Swift 3 and higher this would now be written as:
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.string(from: date)
See answer from Gary Makin. And you need change the format or data. Because the data that you have do not fit under the chosen format. For example this code works correct:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let dateObj = dateFormatter.dateFromString("10 10 2001")
print("Dateobj: \(dateObj)")

Resources