5 Replies
      Latest reply on Oct 21, 2018 5:02 AM by eskimo
      sleipn1r Level 1 Level 1 (0 points)

        Hi Developer's

        get following wrong Date from string

         

        extension DateFormatter {

            convenience init(dateFormat: String) {

                self.init()

                self.locale = Locale.current

                self.timeZone = TimeZone.current

                self.dateFormat =  dateFormat

            }

        }

         

        extension Date{

          func getCurrentTimestamp()->String{

                let formatter = DateFormatter()

                formatter.timeZone = TimeZone.current

                formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

                return(String(describing:formatter.string(from: self)))

            }

        }

         

        let dateFormatter = DateFormatter(dateFormat: "HH:mm")

        let myDate =  dateFormatter.date(from: "10:30")

         

        print myDate

        2000-01-01 08:55:00 +0000

         

        print TimeZone,current

        "Europe/Berlin"

         

        print Locale.current.description

        "de_DE (current)"

         

        print Date().getCurrentTimeStamp()

        2018-10-14 03:56:23"

         

         

        what is going on here... :O :O

         

        on last Verion of Xcode and Beta too

         

        thank's for any suggestions

        • Re: wrong date
          Claude31 Level 8 Level 8 (8,355 points)

          Can you explain where you see an error : what did you expect ? What did you get ?

           

          I tested in playGround, seems OK.

           

          When you use

          let dateFormatter = DateFormatter(dateFormat: "HH:mm")

          let myDate =  dateFormatter.date(from: "10:30")

           

          then only hh:mm are used, and date is set by default to 2000-01-01

          • Re: wrong date
            eskimo Apple Staff Apple Staff (13,325 points)

            The code you’ve posted in problematic in many ways, and it’s hard to say which of those problems is the one you’re investigating and which of them are just your test code.  For example, this code:

            extension DateFormatter {
                convenience init(dateFormat: String) {
                    self.init()
                    self.locale = Locale.current
                    self.timeZone = TimeZone.current
                    self.dateFormat =  dateFormat
                }
            }
            
            let dateFormatter = DateFormatter(dateFormat: "HH:mm")

            is problematic because it’s using a fixed-format date string to set up a date formatter that’s obviously intended to be used for localised dates (based on your setting of the locale property).  When you try to mix fixed-format date strings and localised date you inevitably run into problems (QA1480 NSDateFormatter and Internet Dates explains one of the potential gotchas here, but there are many more).

            So, can you explain more about what you’re trying to achieve here?

            Share and Enjoy

            Quinn “The Eskimo!”
            Apple Developer Relations, Developer Technical Support, Core OS/Hardware
            let myEmail = "eskimo" + "1" + "@apple.com"

              • Re: wrong date
                sleipn1r Level 1 Level 1 (0 points)

                Hi,

                 

                sure,the date and time is wrong (see print timestamp)

                 

                i want to get a new date only the HH.mm is given and (add with Int(min))

                (get only HH:mm) as initial Value.

                 

                for example time is 10:30 AM (add 45min)

                expected the correct Date is as Year and month,(10:30 + 45 min) is 2018-10-18 11:15 AM

                why is the date 2000 ???? as you can see the current Timestamp is correct.

                  • Re: wrong date
                    Claude31 Level 8 Level 8 (8,355 points)

                    If you want to set the hour of today, could use:

                     

                    let otherDate = Calendar.current.date(bySettingHour: 10, minute: 30, second: 0, of: Date())!
                    let dateFormatter = DateFormatter()
                    dateFormatter.dateFormat = "yyyy-MM-dd hh:mm"
                    dateFormatter.timeZone = TimeZone(abbreviation: "UTC+2")     // select your time zone
                    let str = dateFormatter.string(from: otherDate)
                    • Re: wrong date
                      eskimo Apple Staff Apple Staff (13,325 points)

                      I think I see what you’re getting at here.

                      The problem is that Date represents a fixed point in time, so if you ask DateFormatter to parse a string that only contains time components, it has to come up with some default values for the date.  It does this using the defaultDate property.  By default this is nil, which is treated like the start of the year 2000 UTC.  Hence a date formatter with no date components will default to 1 Jan 2000.

                      let df = DateFormatter()
                      df.locale = Locale(identifier: "en_US_POSIX")
                      df.timeZone = TimeZone(secondsFromGMT: 0)
                      df.dateFormat = "HH':'mm"
                      print(df.date(from: "12:34")!)  // prints "2000-01-01 12:34:00 +0000"

                      IMPORTANT Using a value of nil for defaultDate is not the same as using Date(timeIntervalSinceReferenceDate: 0.0).  The reference date used by Date is the start of the year 2001.  I’m sure there’s a good reason for this mismatch (-:

                      If you want the date formatter to default to some other date, just set the defaultDate parameter.

                      df.defaultDate = Date(timeIntervalSinceReferenceDate: 561816000.0)  // 2018-10-21 12:00:00 UTC
                      print(df.date(from: "12:34")!)  // prints "2018-10-21 12:34:00 +0000"

                      WARNING In this example I’m force unwrapping the resulting date.  That’s safe because every time is valid for every date in UTC.  This is not true for all time zones, and that can cause problems on days where daylight savings time ‘springs forward’.  For example:

                      let df = DateFormatter()
                      df.locale = Locale(identifier: "en_US_POSIX")
                      df.timeZone = TimeZone(identifier: "Europe/London")
                      df.dateFormat = "HH':'mm"
                      
                      df.defaultDate = Date(timeIntervalSinceReferenceDate: 543672000.0)  // 2018-03-25 12:00:00 UTC
                      print(df.date(from: "01:30"))  // prints nil

                      This is because the UK transitioned from GMT to BST on 25 Mar 2018, hence 01:30 does not exist on that day.

                      Beyond that, there are still problems associated with the locale.  So far you’ve not clarified whether you’re working with fixed-format dates or localised dates.  If it’s the former then hard coding en_US_POSIX is the right solution; if it’s the latter, things get more complex.

                      Share and Enjoy

                      Quinn “The Eskimo!”
                      Apple Developer Relations, Developer Technical Support, Core OS/Hardware
                      let myEmail = "eskimo" + "1" + "@apple.com"