编程中经常会使用到日期时间,NSDate使用率应该不低。得到它的对象之后,往往我们更关心的是它对应的字符串,要把它转换成字符串,就要使用NSDateFormatter这个类,
借助这个类可以轻松完成我们想要的由NSDate到NSString 或者由 NSStrinngn 到NSDate的转换。
还有一个和时间日期有关的类,有兴趣的童鞋闷可以去瞧瞧 NSCalendarDate ,反正我已经对它不感兴趣了。
下面是其简单用法:
//
// main.m
// HelloWorld
//
// Created by Moluth on 17/4/6.
// Copyright (c) 2017年 Moluth. All rights reserved.
//
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
NSDate *date=[[NSDate alloc] init];//创建一个NSDate对象,时间为当前系统时间
NSDateFormatter *formatter=[[NSDateFormatter alloc] init];//创建日期格式转换器
[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];//时间格式
NSString *dstr=[formatter stringFromDate:date];//通过formatter 把日期转换成字符串
NSLog(@"%@",dstr);//2017-04-06 03:37:02
NSDate *date2=[formatter dateFromString:dstr];
//见名知意
[date initWithTimeIntervalSince1970:33333333l];
[date timeIntervalSince1970];
return 0;//返回值
}