Our first example demonstrates how to work with times and durations in Objective-C. Here’s the full source code:
Let’s break down the key points:
We start by getting the current time using [NSDate date].
We create a specific date using NSDateComponents and NSCalendar. This is equivalent to the time.Date() function in Go.
We can extract various components of the date using the NSDateComponents properties.
The weekday can be obtained using the NSCalendarUnitWeekday component.
We can compare dates using the compare: method, which returns an NSComparisonResult.
To get the duration between two dates, we use timeIntervalSinceDate:, which returns a number of seconds as an NSTimeInterval.
We can perform various calculations with this interval, such as converting to hours, minutes, etc.
Finally, we can add or subtract time intervals from dates using dateByAddingTimeInterval:.
To run this program, save it as TimeExample.m and compile it with:
Then run it with:
This will output the current time, the specified time, and various calculations and comparisons between them.
Note that Objective-C uses the NSDate class and related Foundation framework classes for date and time operations, which offer similar functionality to Go’s time package, but with a different API.