How to get a unix timestamp for specific hour?

How can you get a unix timestamp for a specific timepoint? For example how would I convert current day 16:30 ET time to a timestamp ?

1 answer

  • answered 2020-11-24 21:41 Leo Dabus

    You can use calendar method date(bySettingHour:) and set the desired time.

    let now = Date()
    if let currentTimezoneTimeStamp = Calendar.current.date(bySettingHour: 16, minute: 30, second: 0, of: now)?.timeIntervalSince1970 {
        currentTimezoneTimeStamp  // 1606246200  "GMT-3"
    }
    

    If you need to specify a specific timezone you can set the calendar's timezone property:

    var calendar = Calendar.current
    calendar.timeZone = TimeZone(identifier: "America/New_York")!
    if let newYorkTimeStamp = calendar.date(bySettingHour: 16, minute: 30, second: 0, of: now)?.timeIntervalSince1970 {
        newYorkTimeStamp          // 1606253400  "GMT-5"
    }