Get Current Hour in Military Time with SwiftUI | Hacking Swift 5.5, Xcode 13, and iOS 15

Display the Hour with Swift

by Alexandra Kropova from Mammoth Interactive
Want to learn more? Enroll in Complete Web & App Development with Machine Learning For All (125 Hours). Free in the Mammoth Unlimited Membership. Get 250+ courses and 2,000 hours at a dirt-cheap price.
To get the current hour, use the following Swift 5.5 code:
func createFormatter() -> String {
    
    let components = Calendar.current.dateComponents([.hour], from: Date())
    let hour = components.hour ?? 0
    
    return String(hour)

Understanding this function:

The function name is createFormatter. The function takes in no parameters (arguments). The Date object is instantiated with Date() to get the current date AND time. The Calendar object from SwiftUI is used to get the hour component of the current date. The dateComponents() function returns a list of components, in this case 1 item in the list (the hour component). The hour constant can be created by accessing a property of components. The hour property is optional, meaning it may or may not have a value. Therefore, we must give it a default value if no value is able to be fetched. The default value we’ve used is 0. The function returns the hour (an optional Integer) converted to a String. Suggest more solutions or ask a question in the comments below.
Want to learn more? Enroll in Complete Web & App Development with Machine Learning For All (125 Hours). Free in the Mammoth Unlimited Membership. Get 250+ courses and 2,000 hours at a dirt-cheap price.
Mammoth Interactive Favicon

Why you NEED to take this course :

Get in Touch.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

EMAIL US

support@mammothinteractive.com