Main.m
int main(int argc, const char * argv[])
{
/*_____________________NSDate的使用______________________________*/
//1.创建日期
NSDate *date1 = [NSDate date]; //创建了一个当前时间点的日期对象,0时区
NSDate *date2 = [[NSDate alloc] init];
NSLog(@"date2:%@",date2);
//在当前日期的基础上累加一个日期之后的日期对象,单位是秒
//明天
NSDate *date3 = [NSDate dateWithTimeIntervalSinceNow:24*60*60];
NSLog(@"date3:%@",date3);
//昨天
NSDate *date4 = [NSDate dateWithTimeIntervalSinceNow:-24*60*60];
NSLog(@"date4:%@",date4);
//时间戳:某一个日期到1970年的秒数大小,称为该日期的时间戳
//距离1970年一段时间后的日期
NSDate *date1970 = [NSDate dateWithTimeIntervalSince1970:0];
NSLog(@"date1970:%@",date1970);
NSDate *date5 = [NSDate dateWithTimeIntervalSince1970:1410334559.697678 + 24*60*60];
NSLog(@"date5:%@",date5);
//2.获取时间戳
NSDate *dateNow = [NSDate date]; //当前日期对象
NSTimeInterval t1 = [dateNow timeIntervalSince1970];
NSLog(@"t1:%f",t1);
//距离现在的秒数
NSTimeInterval t2 = [date5 timeIntervalSinceNow];
NSLog(@"%f",t2);
NSTimeInterval t3 = [date5 timeIntervalSinceDate:dateNow];
NSLog(@"t3:%f",t3);
//3.日期比较
//(1)compare
NSComparisonResult result = [date3 compare:date4];
if (result == NSOrderedAscending) {
NSLog(@"date3 < date4");
}else if (result == NSOrderedDescending) {
NSLog(@"date3 > date4");
}else {
NSLog(@"date3 = date4");
}
//(2)通过时间戳比较
// [date3 timeIntervalSince1970]; //date3的时间戳
// [date4 timeIntervalSince1970]; //date4的时间戳
if ([date3 timeIntervalSince1970] > [date4 timeIntervalSince1970]) {
NSLog(@"date3 > date4");
}
// 2014-09-10 07:42:55 +0000
// 2014年09月10日 07时42分55秒 +0000
/*________________________日期格式化__________________________________*/
//1.创建日期对象
NSDate *date6 = [NSDate date];
NSLog(@"%@",date6);
// 2014-09-10 07:45:15 +0000
//创建日期格式对象
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//设置一个日期格式
[dateFormatter setDateFormat:@"yyyy年MM月dd日 HH时mm分ss秒 zz"];
//将日期对象转换成字符串
NSString *stringDate1 = [dateFormatter stringFromDate:date6];
NSLog(@"stringDate1:%@",stringDate1);
//设置时区
//创建时区对象
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Indian/Christmas"];
//将时区对象配置给dateFormatter
[dateFormatter setTimeZone:timeZone];
NSString *stringDate2 = [dateFormatter stringFromDate:date6];
NSLog(@"stringDate2:%@",stringDate2);
//获取所有时区的名字
// NSArray *zoneNames = [NSTimeZone knownTimeZoneNames];
// NSLog(@"zoneName:%@",zoneNames);
//2.将字符串格式化对象转换成日期对象
// 2014年09月10日 15时59分28秒 GMT+8
NSString *string = @"2014年09月10日 15时59分28秒 GMT+8";
NSDateFormatter *dateformatter1 = [[NSDateFormatter alloc] init];
//设置格式
[dateformatter1 setDateFormat:@"yyyy年MM月dd日 HH时mm分ss秒 zz"];
NSDate *date = [dateformatter1 dateFromString:string];
NSLog(@"date:%@",date);
return 0;
}