Getting 24 hour time from Date

Does anyone have the format string to use to just get the 24 hour time (no am/pm) indicator from Date?

I can't seem to get 24 hour time with:

let now = Date()
now.formatted(date:.omitted,time:.complete) // Or any of the time options.

Replies

Is this something you plan to present to the user? Or a value that you’re working with programmatically, for example, passing to a back-end server?

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

  • The user is to give me a 24 hour time, which I then programmatically check for when to enable/disable certain features in a multi week running programming

Add a Comment

You can use a locale identifier that overrides the hour cycle: https://unicode.org/reports/tr35/#UnicodeHourCycleIdentifier

The user is to give me a 24 hour time, which I then programmatically check for when to enable/disable certain features

I’m a bit confused by that first bit. If the user is giving you a 24-hour time, why do you need to get one from a Date value?

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

The user says (and by user , it ia s control file that is read by the controller at startup). It is a range of a 24 hour day. The "master controller", which runs all the time, is looking to see if at any given time, time "now" is between that range. if it is, it then does certain things.

In c++, this was converted to an integer (and it was a simple comparasion, just had to handle the rollover at midnight). As I convert to swift/macOS, not as clear cut how to get time now in just a 24 hour time.

OK, the date formatting APIs are not the right path forward for you because they are primarily focused on the presenting dates to the user. To work with dates and times, use the calendar and date component APIs. For example:

import Foundation

func main() {
    let c = Calendar(identifier: .gregorian)
    let d1 = Date(timeIntervalSinceReferenceDate: 3.0 * 60.0 * 60.0)
    print(c.component(.hour, from: d1))     // 3
    let d2 = Date(timeIntervalSinceReferenceDate: 15.0 * 60.0 * 60.0)
    print(c.component(.hour, from: d2))     // 15
}

main()

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"