object c NSDate

本文介绍如何使用Objective-C进行日期和时间的操作,包括获取当前日期、时间加减、时区转换及日期比较等。同时展示了NSDateFormatter用于日期格式化的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//
//  main.m
//  DateDemo
//
//  Created by 千雅爸爸 on 16/10/7.
//  Copyright © 2016年 kodulf. All rights reserved.
//

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        //oc 日期操作,和java几乎是一模一样,有区别的是这里的Date是直接格林尼治时间,java直接是系统的时间。
        NSDate *date = [NSDate date];
        NSLog(@"%@",date);//格林尼治时间
        
        //如何获取往前,往后的时间
        date = [[NSDate alloc] initWithTimeInterval:60 sinceDate:date];
        NSLog(@"60 秒以后的时间%@",date);//注意这里是60秒,而不是毫秒
    
        //进行时区的转换,首先获取系统的当前的时区
        NSTimeZone *zone = [NSTimeZone systemTimeZone];
        NSInteger interval = [zone secondsFromGMT];//获取时间差
        NSDate *localDate = [date dateByAddingTimeInterval:interval];
        NSLog(@"本地时间:%@",localDate);
        
        //如何对两个日期,进行日期的比较
        NSDate *currentDate =[NSDate date];
        NSDate *laterDate = [[NSDate alloc] initWithTimeInterval:60*60 sinceDate:currentDate];
        NSDate *earlierDate = [[NSDate alloc] initWithTimeInterval:-60 sinceDate:currentDate];
        
        if([currentDate laterDate:laterDate]){//这个方法说的是后面的是
            NSLog(@"currentDate: %@日期比laterDate:%@晚",currentDate,laterDate);
        }
        
        if([currentDate earlierDate:earlierDate]){
            NSLog(@"currentDate: %@日期比earlierDate:%@早",currentDate,earlierDate);
        }
        //通过compare来比较
        if([currentDate compare:earlierDate] ==NSOrderedDescending){
            NSLog(@"晚");
        }
        
        //nsdate 和nsstring的比较
        NSDate *date1 = [NSDate date];
        //日期格式化对象
        NSDateFormatter *dateFormatter
        = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy年MM月dd HH:mm:ss zzz"];//zzz表示时区,注意标准的应该是yyyy-MM-dd HH:mm:ss zzz,这里使用年,月是为了看的清楚一些。
        NSString *dateString = [dateFormatter stringFromDate:date1];
        NSLog(@"%@",dateString);
        
        dateString = @"2016年01月01 18:18:18";
        dateFormatter =[[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy年MM月dd HH:mm:ss"];
        date1 = [dateFormatter dateFromString:dateString];
        NSLog(@"%@",date1);
    
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值