关于OC中得日期时间类,看这些够用啦(^__^) 嘻嘻……
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// NSDate 时间日期类 NSData 二进制数据流
{
// 1 . 获取当前的时间 零时区的时间
NSDate *date = [NSDate date];
NSLog(@"%@",date);//显示的是格林尼治时间:年-月-日 时:分:秒 +时区
// 2 .本地时间 东八区 , 晚八个小时
NSDate *currentDate = [NSDate dateWithTimeIntervalSinceNow:8*60*60];
NSLog(@"%@",currentDate);
// 3 . 昨天此时
NSDate *yesterdayDate = [NSDate dateWithTimeIntervalSinceNow:-1*16*60*60];
NSLog(@"%@",yesterdayDate);
// 4. 明天此刻
NSDate *tomorrowDate = [NSDate dateWithTimeInterval:24*60*60 sinceDate:currentDate];
NSLog(@"%@",tomorrowDate);
// 5 . NSTimeInterval 实质是double类型 ,代表的是时间间隔,double的typedef
// 昨天此时与明天此刻的时间间隔
NSTimeInterval timeInterval = [tomorrowDate timeIntervalSinceDate:yesterdayDate];
NSLog(@"%.0f",timeInterval);
//练习
{ // 保证两个日期是在同一个时区
NSDate *current = [NSDate dateWithTimeIntervalSinceNow:8*60*60];
NSLog(@"%@",current);
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:-4000+8*60*60];
NSLog(@"%@",date);
NSTimeInterval timeInterval = [current timeIntervalSinceDate:date];
if (timeInterval < 60) {
NSLog(@"刚刚");
}else if(timeInterval < 60*60)
{
NSLog(@"%.0f分钟前",timeInterval/60);
}else if (timeInterval < 24*3600)
{
NSLog(@"%.0f小时前",timeInterval/3600);
}else if (timeInterval < 365*24*3600)
{
NSLog(@"%.0f天前",timeInterval/24*3600);
}
}
// 7、时间戳:从1970.1.1 到当前时间的时间间隔就叫时间戳 常见于网址中 1970年1月1日0 时0分0秒 计算机元年 32位系统能够表示的最大数 ——2的31次方减1 , 能够表示的最大时间是68.1年,也就是2038年2月份左右 , 64位系统能够表示2924亿年
NSTimeInterval time = [currentDate timeIntervalSince1970];
NSLog(@"%.0f",time);
// 8.NSDateFormatter 日期格式类,主要作用:将NSDate 对象转化为某种格式,然后转化成NSString 对象
//创建NSDateFormatter 对象
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
//设定日期格式:yyyy(年) - MM(月) - dd(日) H(小时) m (分钟)s(秒)
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date1 = [NSDate date];
//日期转字符串 系统认为date是零时区的时间,转成字符串是东八区的
NSString *datestring = [formatter stringFromDate:date1];
NSLog(@"%@",datestring);
// 字符串转date
{
// 系统认为字符串是东八区的时间,转成NSDate是零时区的
NSString *dateStr = @"2011年11月11日 19时11分11秒";
NSDateFormatter *formater = [[NSDateFormatter alloc]init];
[formater setDateFormat:@"yyyy年MM月dd日 HH时mm分ss秒"];
NSDate *date = [formater dateFromString:dateStr];
NSLog(@"%@",date);
}
}