Elysia Tools
Navigation
Objective-C
Objective-C: Elapsed seconds are not calendar days, Floor differs from truncation, Skip only the defined weekend
Choose a code card, follow fixed inputs, and distinguish local calculations from real device or server behavior.
Samples
Entries inside this sample collection
NSDate Basics
Create, manipulate, and compare dates using NSDate
Difficulty
5/10
Estimated time
25 min
Tags
objectivec, macos, datetime, nsdate
Prerequisites
Objective-C basics, Foundation framework
// macOS Objective-C NSDate Basics
// Using Foundation framework
#import <Foundation/Foundation.h>
// MARK: - 1. Creating Dates
@interface DateCreation : NSObject
+ (void)demonstrateCreation {
NSLog(@"--- Date Creation ---");
// Current date
NSDate *now = [NSDate date];
NSLog(@"Current date: %@", now);
// Distant past
NSDate *past = [NSDate distantPast];
NSLog(@"Distant past: %@", past);
// Distant future
NSDate *future = [NSDate distantFuture];
NSLog(@"Distant future: %@", future);
// Tomorrow
NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:86400];
NSLog(@"Tomorrow: %@", tomorrow);
// Yesterday
NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow:-86400];
NSLog(@"Yesterday: %@", yesterday);
// Specific date
NSDateComponents *components = [[NSDateComponents alloc] init];
components.year = 2024;
components.month = 12;
components.day = 25;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *christmas = [calendar dateFromComponents:components];
NSLog(@"Christmas 2024: %@", christmas);
// From string
NSString *dateString = @"2024-12-25 14:30:00";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *parsed = [formatter dateFromString:dateString];
NSLog(@"Parsed date: %@", parsed);
// Unix timestamp
NSDate *fromTimestamp = [NSDate dateWithTimeIntervalSince1970:1703500000];
NSLog(@"From timestamp: %@", fromTimestamp);
}
@end
// MARK: - 2. Date Comparison
@interface DateComparison : NSObject
+ (void)demonstrateComparison {
NSLog(@"\n--- Date Comparison ---");
NSDate *now = [NSDate date];
NSDate *past = [NSDate dateWithTimeIntervalSinceNow:-3600];
NSDate *future = [NSDate dateWithTimeIntervalSinceNow:3600];
// Compare
NSComparisonResult result = [now compare:past];
if (result == NSOrderedAscending) {
NSLog(@"Now < Past");
} else if (result == NSOrderedDescending) {
NSLog(@"Now > Past");
} else {
NSLog(@"Now == Past");
}
// Earlier/Later
BOOL isEarlier = ([past compare:now] == NSOrderedAscending);
BOOL isLater = ([future compare:now] == NSOrderedDescending);
NSLog(@"Past is earlier than now: %@", isEarlier ? @"YES" : @"NO");
NSLog(@"Future is later than now: %@", isLater ? @"YES" : @"NO");
// Between dates
NSDate *start = [NSDate dateWithTimeIntervalSinceNow:-7200];
NSDate *end = [NSDate dateWithTimeIntervalSinceNow:7200];
BOOL isBetween = ([now compare:start] == NSOrderedDescending) &&
([now compare:end] == NSOrderedAscending);
NSLog(@"Now is between start and end: %@", isBetween ? @"YES" : @"NO");
// Equal dates (within tolerance)
NSDate *date1 = [NSDate date];
[NSThread sleepForTimeInterval:0.1];
NSDate *date2 = [NSDate date];
NSTimeInterval tolerance = 1.0; // 1 second
BOOL isEqual = fabs([date1 timeIntervalSinceDate:date2]) < tolerance;
NSLog(@"Dates equal (within %.0fs): %@", tolerance, isEqual ? @"YES" : @"NO");
}
@end
// MARK: - 3. Date Intervals
@interface DateIntervals : NSObject
+ (void)demonstrateIntervals {
NSLog(@"\n--- Date Intervals ---");
NSDate *start = [NSDate date];
// Time interval since date
NSTimeInterval interval = [start timeIntervalSinceNow];
NSLog(@"Interval since now: %.0f seconds", interval);
// Add time interval
NSDate *plusOneHour = [start dateByAddingTimeInterval:3600];
NSLog(@"Plus one hour: %@", plusOneHour);
// Days from now
NSDate *sevenDaysLater = [NSDate dateWithTimeIntervalSinceNow:7 * 86400];
NSLog(@"Seven days later: %@", sevenDaysLater);
// Days ago
NSDate *thirtyDaysAgo = [NSDate dateWithTimeIntervalSinceNow:-30 * 86400];
NSLog(@"Thirty days ago: %@", thirtyDaysAgo);
// Time between dates
NSDate *date1 = [NSDate dateWithTimeIntervalSince1970:0];
NSDate *date2 = [NSDate date];
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
NSLog(@"Seconds between dates: %.0f", secondsBetween);
NSInteger daysBetween = floor(secondsBetween / 86400);
NSLog(@"Days between: %ld days", (long)daysBetween);
// Calculate age
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd";
NSDate *birthDate = [formatter dateFromString:@"1990-06-15"];
NSTimeInterval ageInSeconds = [[NSDate date] timeIntervalSinceDate:birthDate];
NSInteger ageInYears = floor(ageInSeconds / (365.25 * 24 * 3600));
NSLog(@"Age: %ld years", (long)ageInYears);
}
@end
// MARK: - 4. NSDateFormatter
@interface DateFormatting : NSObject
+ (void)demonstrateFormatting {
NSLog(@"\n--- Date Formatting ---");
NSDate *now = [NSDate date];
// Predefined styles
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateStyle = NSDateFormatterShortStyle;
formatter.timeStyle = NSDateFormatterNoStyle;
NSLog(@"Short date: %@", [formatter stringFromDate:now]);
formatter.dateStyle = NSDateFormatterMediumStyle;
formatter.timeStyle = NSDateFormatterShortStyle;
NSLog(@"Medium date, short time: %@", [formatter stringFromDate:now]);
formatter.dateStyle = NSDateFormatterLongStyle;
formatter.timeStyle = NSDateFormatterLongStyle;
NSLog(@"Long date, long time: %@", [formatter stringFromDate:now]);
formatter.dateStyle = NSDateFormatterFullStyle;
formatter.timeStyle = NSDateFormatterFullStyle;
NSLog(@"Full style: %@", [formatter stringFromDate:now]);
// Custom formats
formatter.dateFormat = @"yyyy-MM-dd";
NSLog(@"ISO date: %@", [formatter stringFromDate:now]);
formatter.dateFormat = @"MMMM dd, yyyy";
NSLog(@"Readable: %@", [formatter stringFromDate:now]);
formatter.dateFormat = @"HH:mm:ss";
NSLog(@"Time: %@", [formatter stringFromDate:now]);
formatter.dateFormat = @"EEEE, MMMM d, yyyy 'at' h:mm a";
NSLog(@"Friendly: %@", [formatter stringFromDate:now]);
// Relative date formatting
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateFormatter *relativeFormatter = [[NSDateFormatter alloc] init];
relativeFormatter.dateStyle = NSDateFormatterShortStyle;
relativeFormatter.timeStyle = NSDateFormatterShortStyle;
relativeFormatter.doesRelativeDateFormatting = YES;
NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow:-86400];
NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:86400];
NSLog(@"Yesterday: %@", [relativeFormatter stringFromDate:yesterday]);
NSLog(@"Tomorrow: %@", [relativeFormatter stringFromDate:tomorrow]);
// Locale
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"fr_FR"];
formatter.dateFormat = @"MMMM dd, yyyy";
NSLog(@"French locale: %@", [formatter stringFromDate:now]);
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"de_DE"];
NSLog(@"German locale: %@", [formatter stringFromDate:now]);
// Parse from string
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSString *dateString = @"2024-12-25 15:30:00";
NSDate *parsed = [formatter dateFromString:dateString];
NSLog(@"Parsed: %@", parsed);
}
@end
// MARK: - 5. NSCalendar and Components
@interface CalendarOperations : NSObject
+ (void)demonstrateCalendar {
NSLog(@"\n--- NSCalendar Operations ---");
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
// Extract components
NSDateComponents *components = [calendar componentsInTimeZone:[NSTimeZone systemTimeZone]
fromDate:now];
NSLog(@"Year: %ld", (long)components.year);
NSLog(@"Month: %ld", (long)components.month);
NSLog(@"Day: %ld", (long)components.day);
NSLog(@"Hour: %ld", (long)components.hour);
NSLog(@"Minute: %ld", (long)components.minute);
NSLog(@"Second: %ld", (long)components.second);
// Weekday
NSLog(@"Weekday: %ld", (long)components.weekday);
// Week of year
NSLog(@"Week of year: %ld", (long)components.weekOfYear);
// Specific components
NSInteger year = [calendar component:NSCalendarUnitYear fromDate:now];
NSInteger month = [calendar component:NSCalendarUnitMonth fromDate:now];
NSInteger day = [calendar component:NSCalendarUnitDay fromDate:now];
NSLog(@"Date: %ld-%02ld-%02ld", (long)year, (long)month, (long)day);
// First day of month
NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:now];
NSLog(@"Days in month: %lu", (unsigned long)range.length);
// Start of day
NSDate *startOfDay = [calendar startOfDayForDate:now];
NSLog(@"Start of day: %@", startOfDay);
// End of day
NSDate *endOfDay = [calendar dateBySettingHour:23 minute:59 second:59 ofDate:now options:0];
NSLog(@"End of day: %@", endOfDay);
// Week bounds
NSDate *startOfWeek = [calendar dateFromComponents:[calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekday | NSCalendarUnitDay forDate:now]];
components.weekday = calendar.firstWeekday;
components.day = components.day - (components.weekday - calendar.firstWeekday);
NSDate *weekStart = [calendar dateFromComponents:components];
NSLog(@"Start of week: %@", weekStart);
}
@end
// MARK: - 6. Date Arithmetic
@interface DateArithmetic : NSObject
+ (void)demonstrateArithmetic {
NSLog(@"\n--- Date Arithmetic ---");
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
// Add components
NSDateComponents *addComponents = [[NSDateComponents alloc] init];
addComponents.day = 7;
addComponents.month = 1;
NSDate *futureDate = [calendar dateByAddingComponents:addComponents toDate:now options:0];
NSLog(@"Plus 1 month and 7 days: %@", futureDate);
// Subtract components
NSDateComponents *subtractComponents = [[NSDateComponents alloc] init];
subtractComponents.month = -3;
NSDate *pastDate = [calendar dateByAddingComponents:subtractComponents toDate:now options:0];
NSLog(@"Minus 3 months: %@", pastDate);
// Add years
NSDateComponents *yearComponents = [[NSDateComponents alloc] init];
yearComponents.year = 1;
NSDate *nextYear = [calendar dateByAddingComponents:yearComponents toDate:now options:0];
NSLog(@"Next year: %@", nextYear);
// Last day of month
NSDate *endOfMonth = [calendar dateByAddingUnit:NSCalendarUnitMonth value:1 toDate:now options:0];
NSDateComponents *endOfMonthComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth fromDate:endOfMonth];
endOfMonthComponents.day = 0;
endOfMonth = [calendar dateFromComponents:endOfMonthComponents];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd";
NSLog(@"End of month: %@", [formatter stringFromDate:endOfMonth]);
// Business days (simplified)
NSDate *fiveBusinessDays = [self addBusinessDays:5 toDate:now calendar:calendar];
NSLog(@"5 business days later: %@", [formatter stringFromDate:fiveBusinessDays]);
}
+ (NSDate *)addBusinessDays:(NSInteger)days toDate:(NSDate *)date calendar:(NSCalendar *)calendar {
NSDate *result = date;
NSInteger added = 0;
while (added < days) {
result = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:result options:0];
NSDateComponents *comps = [calendar components:NSCalendarUnitWeekday fromDate:result];
// Skip weekends (Saturday = 7, Sunday = 1)
if (comps.weekday != 1 && comps.weekday != 7) {
added++;
}
}
return result;
}
@end
// MARK: - 7. Time Zones
@interface TimeZoneOperations : NSObject
+ (void)demonstrateTimeZones {
NSLog(@"\n--- Time Zone Operations ---");
NSDate *now = [NSDate date];
// System timezone
NSTimeZone *systemTZ = [NSTimeZone systemTimeZone];
NSLog(@"System timezone: %@", systemTZ.name);
NSLog(@"Abbreviation: %@", systemTZ.abbreviation);
// UTC timezone
NSTimeZone *utcTZ = [NSTimeZone timeZoneWithName:@"UTC"];
NSLog(@"UTC offset: %@", [systemTZ secondsFromGMTForDate:now] > 0 ? @"+" : @"");
NSLog(@"Seconds from GMT: %ld", (long)[systemTZ secondsFromGMTForDate:now]);
// Convert timezones
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss z";
formatter.timeZone = utcTZ;
NSLog(@"UTC: %@", [formatter stringFromDate:now]);
formatter.timeZone = [NSTimeZone timeZoneWithName:@"America/New_York"];
NSLog(@"New York: %@", [formatter stringFromDate:now]);
formatter.timeZone = [NSTimeZone timeZoneWithName:@"Europe/London"];
NSLog(@"London: %@", [formatter stringFromDate:now]);
formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Tokyo"];
NSLog(@"Tokyo: %@", [formatter stringFromDate:now]);
// Available timezones
NSArray *timezoneNames = [NSTimeZone knownTimeZoneNames];
NSLog(@"\nAvailable timezones (first 10):");
for (NSString *name in [timezoneNames subarrayWithRange:NSMakeRange(0, 10)]) {
NSTimeZone *tz = [NSTimeZone timeZoneWithName:name];
NSLog(@" %@ (GMT%@%ldh)",
name,
[tz secondsFromGMT] >= 0 ? @"+" : @"",
(long)([tz secondsFromGMT] / 3600));
}
}
@end
// MARK: - 8. Utility Functions
@interface DateUtilities : NSObject
+ (BOOL)isToday:(NSDate *)date {
NSCalendar *calendar = [NSCalendar currentCalendar];
return [calendar isDateInToday:date];
}
+ (BOOL)isYesterday:(NSDate *)date {
NSCalendar *calendar = [NSCalendar currentCalendar];
return [calendar isDateInYesterday:date];
}
+ (BOOL)isTomorrow:(NSDate *)date {
NSCalendar *calendar = [NSCalendar currentCalendar];
return [calendar isDateInTomorrow:date];
}
+ (BOOL)isThisWeek:(NSDate *)date {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
NSDate *startOfWeek;
NSTimeInterval interval;
[calendar rangeOfUnit:NSCalendarUnitWeekOfMonth
startDate:&startOfWeek
interval:&interval
forDate:now];
return [date compare:startOfWeek] != NSOrderedAscending &&
[date compare:[startOfWeek dateByAddingTimeInterval:interval]] != NSOrderedDescending;
}
+ (BOOL)isThisMonth:(NSDate *)date {
NSCalendar *calendar = [NSCalendar currentCalendar];
return [calendar isDateInThisMonth:date];
}
+ (BOOL)isThisYear:(NSDate *)date {
NSCalendar *calendar = [NSCalendar currentCalendar];
return [calendar isDateInThisYear:date];
}
+ (NSInteger)daysBetween:(NSDate *)from and:(NSDate *)to {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitDay
fromDate:to
toDate:from
options:0];
return labs(components.day);
}
+ (void)demonstrateUtilities {
NSLog(@"\n--- Utility Functions ---");
NSDate *today = [NSDate date];
NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow:-86400];
NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:86400];
NSDate *lastWeek = [NSDate dateWithTimeIntervalSinceNow:-7 * 86400];
NSDate *lastMonth = [NSDate dateWithTimeIntervalSinceNow:-30 * 86400];
NSLog(@"Today is today: %@", [self isToday:today] ? @"YES" : @"NO");
NSLog(@"Yesterday is yesterday: %@", [self isYesterday:yesterday] ? @"YES" : @"NO");
NSLog(@"Tomorrow is tomorrow: %@", [self isTomorrow:tomorrow] ? @"YES" : @"NO");
NSLog(@"Last week is this week: %@", [self isThisWeek:lastWeek] ? @"YES" : @"NO");
NSLog(@"Last month is this month: %@", [self isThisMonth:lastMonth] ? @"YES" : @"NO");
NSInteger days = [self daysBetween:yesterday and:tomorrow];
NSLog(@"Days between yesterday and tomorrow: %ld", (long)days);
}
@end
// MARK: - Main Demonstration
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSLog(@"=== macOS Objective-C NSDate Examples ===\n");
// 1. Creation
[DateCreation demonstrateCreation];
// 2. Comparison
[DateComparison demonstrateComparison];
// 3. Intervals
[DateIntervals demonstrateIntervals];
// 4. Formatting
[DateFormatting demonstrateFormatting];
// 5. Calendar
[CalendarOperations demonstrateCalendar];
// 6. Arithmetic
[DateArithmetic demonstrateArithmetic];
// 7. Timezones
[TimeZoneOperations demonstrateTimeZones];
// 8. Utilities
[DateUtilities demonstrateUtilities];
NSLog(@"\n=== NSDate Examples Completed ===");
}
return 0;
}Tools
Tools frequently paired with this sample
Related
Related sample collections
Related