31

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.

kj007
  • 6,073
  • 4
  • 29
  • 47
Paolo Gdf
  • 759
  • 3
  • 10
  • 15
  • unrelated to the issue, but: are you sure having an empty text or status of a message makes sense? Seems like a pretty unreasonable default value – Alexander Jan 03 '17 at 03:09
  • Your code shown causes different error than yours: **error: incorrect argument label**. (`data:` needs to be `date:`?) Please show code exactly the same as which is causing the issue. You'd also better to show how `elemMessage` is declared. And this is not a critical issue, but you'd better use UpperCamelCase for type names. – OOPer Jan 03 '17 at 03:27
  • sorry argument label is `date:` copy error. `elemMessage` is json parse from dbase and it works. I have error on `date` – Paolo Gdf Jan 03 '17 at 03:31
  • Swift is a type inferred language. `var id = "0"` – Leo Dabus Jan 03 '17 at 04:02
  • How do you know your date is UTC? That format looks like local time for me. If it were UTC it would have a Z there or +0000 – Leo Dabus Jan 03 '17 at 04:06
  • Note that you should name your classes and structures starting with an uppercase letter – Leo Dabus Jan 03 '17 at 04:12

3 Answers3

84

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

Output screen.

emehex
  • 9,874
  • 10
  • 54
  • 100
Anand Nimje
  • 6,163
  • 4
  • 24
  • 43
  • 1
    I have used your code but i have error: ` Cannot convert value of type 'Date?' to expected argument type 'Date!' ` when load it in structure message. – Paolo Gdf Jan 03 '17 at 03:38
  • 1
    ***NOTE HOWEVER*** you have to cache date formatters in iOS: http://stackoverflow.com/a/42370648/294884 – Fattie Apr 24 '17 at 13:01
  • 1
    @Andand Nimje : Have you noticed that, one day decremented after the convertion – Vineesh TP Jul 10 '17 at 16:20
  • Let me check @VineeshTP – Anand Nimje Jul 10 '17 at 17:55
  • Thank you so much @VineeshTP for your suggestion. – Anand Nimje Jul 11 '17 at 05:18
  • 5
    shouldn't `mm` be upper case? – mask8 Jul 11 '17 at 08:16
  • 2
    not working ....date are coming incorrect after converting to date – Pulkit Kumar Singh Oct 14 '17 at 11:11
  • @PulkitKumarSingh what problem are you facing can you tell me in details so i can help you. I think are you doing something wrong. – Anand Nimje Oct 14 '17 at 17:53
  • date , month , year was coming incorrect ...time was right ....my date was in format "20-02-2018 06:20" ...i copied your code and then ran it. It was giving current date. – Pulkit Kumar Singh Oct 14 '17 at 18:43
  • if you trying to convert `String` to `Date` then code working fine. @PulkitKumarSingh I can show you Playground screenshot. I think still you not able to understand code. – Anand Nimje Oct 14 '17 at 19:06
  • Please run your code ......I am still not able to convert string to date.....date is coming incorrect...ran again!! – Pulkit Kumar Singh Oct 14 '17 at 20:02
  • If you look closely at the output screen you see you converted July 11, 2017 but actually got January 11, 2017. You want the date format string to be "dd-MM-yyyy" – GilroyKilroy Oct 19 '17 at 22:33
  • mm is minute. MM is month. Single M or double M works. [Date Formaters](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1) > [Date Format Patterns](http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns) – Mark Gerrior Mar 23 '18 at 19:57
  • change "dd-MM-yyyy" instead "dd-mm-yyyy" – oscar castellon Jun 08 '18 at 09:28
17

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"
Rabie
  • 513
  • 5
  • 10
5
 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)

Jeet Gandhi
  • 577
  • 4
  • 5