2

I can't find an accurate answer, but all I want to do is:

  1. user clicks a button and passes in a date in miliseconds
  2. my app opens the IOS default calendar app at that specific date and time.

I was using this code:

let date = Date(timeIntervalSince1970: TimeInterval(timeInMiliFromBackEnd/1000))
let interval = date.timeIntervalSince1970
let url = NSURL(string: "calshow:\(interval)")!
        UIApplication.shared.openURL(url as URL)

The calendar app opens, however it opens in some random year (January 2066 @ 3pm).

Can anyone provide the swift 3 code for this?

Cheers~

TheQ
  • 1,949
  • 10
  • 38
  • 63

1 Answers1

2

iOS Doesn't use timeIntervalSince1970 as it's "epoch date." You should use timeIntervalSinceReferenceDate instead:

//Convert the time from the server into a Date object
let seconds = TimeInterval(timeInMiliFromBackEnd/1000)
let date = Date(timeIntervalSince1970: seconds)

//Convert the Date object into the number of seconds since the iOS "epoch date"
let interval = date.timeIntervalSinceReferenceDate
if let url = URL(string: "calshow:\(interval)") {
  UIApplication.shared.open(url, options: [:], completionHandler: nil)
}

(Code above updated to use newer open(_:options:completionHandler:) method, as opposed to the now-deprecated openURL(_:) method.)

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • I'm working with android as well and i store all my times from 1970, am i able to convert timeIntervalSince1970 to timeIntervialSinceReferenceDate? – TheQ Jan 18 '18 at 04:21
  • 1
    @TheQ But you have a `Date` instance already so there's nothing to convert. Did you try using the code in this answer as-is? – rmaddy Jan 18 '18 at 04:50
  • @rmaddy So i updated my question and added 1 line of code `let date = Date(timeIntervalSince1970: TimeInterval(timeInMiliFromBackEnd/1000))` to maybe clear things up. I can't try the code as is, because @Duncan made a new date object. I got a timeInMili from a backend thats from in 1970 format and I need to be able to use that somehow to open a calendar, but its not opening to the correct date :( – TheQ Jan 18 '18 at 06:14
  • 1
    @TheQ From the `Date` you create using `timeIntervalSince1970` you then access its `timeIntervalSinceReferenceDate`. – rmaddy Jan 18 '18 at 06:16
  • @rmaddy jeez i guess it worked, i feel dumb, no idea what code i was writing. thanks guys – TheQ Jan 18 '18 at 06:25
  • sir could you please help to answer this question, it seems similar but I don't know how to add the title https://stackoverflow.com/questions/61677145/how-to-open-create-event-screen-in-calendar-app-with-populated-data-in-swift – Alexa289 May 08 '20 at 10:38