//
// 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;
}
object c NSDate
最新推荐文章于 2016-10-07 19:39:55 发布