create a function to subtract 10 minutes to current time and print it in swift

You can create a function in Swift that will use the Date and Calendar classes to subtract 10 minutes from the current time and print the result. Here's an example:

main.swift
func printTimeMinus10Minutes() {
    let calendar = Calendar.current
    let tenMinutesAgo = calendar.date(byAdding: .minute, value: -10, to: Date())
    let formatter = DateFormatter()
    formatter.timeStyle = .short
    let formattedTime = formatter.string(from: tenMinutesAgo!)
    print(formattedTime)
}
309 chars
9 lines

In this function, we first create a Calendar instance using the Calendar.current method. We then use the date(byAdding:to:) method to subtract 10 minutes from the current date and time. Next, we create an instance of DateFormatter to format the resulting time string. We set its timeStyle to .short to show only the time portion of the date. Finally, we format the date and time into a string, and print it using print().

To use this function, you can simply call printTimeMinus10Minutes() from anywhere in your Swift code, and it will print the time 10 minutes ago in a formatted string.

gistlibby LogSnag