Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHESPTRUFRDEEN

Elysia Tools

导航

Objective-C

macOS Objective-C 日期时间示例

macOS Objective-C 日期和时间示例,包括NSDate、NSDateFormatter、NSCalendar和时间间隔

案例

这个案例集合中的条目

代码objectivec简单

NSDate基础

使用NSDate创建、操作和比较日期

难度

5/10

预计时间

25 min

标签

objectivec, macos, datetime, nsdate

前置条件

Objective-C basics, Foundation framework

objectivec
// 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;
}

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

相关内容

相关专题

专题

容器发布前的 Dockerfile 与环境配置审查

检查 Dockerfile 规则、镜像引用格式与环境变量重复键,解释预发布和生产配置差异,形成可核对的容器发布记录。

专题

域名上线前的 DNS、DNSSEC 与 HTTPS 验收

先拟定 DNS 区域记录,再核对在线解析、DNSSEC 委派和实际提供的 HTTPS 证书,为域名上线留下可复核的依据。

专题

重复日历与 ICS 日程安排

跨时区规划并验证重复会议,处理工作日、节假日、冲突和 ICS 导出要求。

专题

API Mock 夹具生成与审阅

生成可重复的 Mock 负载,构造符合格式的边界值,发现易混淆字段名,并在共享临时 Mock 服务前完成复核。

首页
工具3208
案例593
可视化469
文件查看器103
专题237
标签333
图像、音频与视频657

图像、音频、视频处理、转换与优化工具

数学、日期与金融646

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色298

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web193

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

本地习惯记录的备份、恢复演练与分享前检查
长文改编 X 串文与 LinkedIn 帖子的事实复核与交付
Markdown 互动课件审校、离线演示与交付
小房间家具布局复核与搬入方案交付
FLAC/WAV 无损音源疑点筛查与证据交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们

Validation

日期时间校验器

验证日期时间格式,包括ISO8601、自定义格式、闰年和月份/日期验证

Text Processing

日期提取器

从文本中提取多种格式的日期,包括中文、ISO和美国格式,提供详细分析和摘要

Format Conversion

日期格式化器

将日期字符串转换为各种格式的日期格式

Utilities

日期格式统一器

将各种日期格式转换为统一格式

Utilities

文本日期格式统一器

在文本内容中查找并统一日期格式

Date & Time

时长格式化器

将时长格式化为各种人类可读格式

Utilities

日期加法器

从日期添加或减去时间段(年、月、日、时、分、秒)

Utilities

日期差异计算器

计算两个日期之间的差异,以多种时间单位表示

Swift

macOS Swift 日期时间示例

macOS Swift 日期时间示例,包括获取当前时间、时间格式化和时间解析

Go

Web Go 日期时间示例

Web Go 日期时间示例,包括获取当前时间、格式化、解析和时区操作

Python

Web Python 日期时间示例

Web Python 日期时间示例,包括获取当前时间、格式化、解析和时区操作

TypeScript

Web TypeScript 日期时间示例

Web TypeScript 日期和时间示例,包括获取当前时间、格式化、解析和操作

C++

Windows 日期时间 - C++ 示例

Windows平台C++日期时间示例,包括时间获取、格式化和解析操作

Objective-C

macOS Objective-C 加密安全示例

macOS Objective-C 加密安全示例,包括哈希计算、对称加密和Base64编码