NSDateFormatter相关整理 -- @ShinePug

NSDateFormatter相关整理

Formatter译为格式,相应的NSDateFormatter就相当于是NSDate的转换类,将NSDate转换为另一种格式,或转换回来。NSDate没有自己的输出,需要借助NSDateFormatter以相应格式输出。这差不多就是NSDateFormatter的作用了吧。

常用的方法并不复杂,几条语句而已,下面就是整个过程了。 懒得写直接复制别人的了

复制代码
//实例化一个NSDateFormatter对象
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//设定时间格式,这里可以设置成自己需要的格式
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//用[NSDate date]可以获取系统当前时间
NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
//输出格式为:2010-10-27 10:22:13
NSLog(@”%@”,currentDateStr);
//alloc后对不使用的对象别忘了release
[dateFormatter release];
复制代码

输出格式通setDateStyle和setTimeStyle设置,分别定义的日期和时间的格式可选一下的系统给出的方法

复制代码
typedef enum {
    NSDateFormatterNoStyle     = kCFDateFormatterNoStyle,
    NSDateFormatterShortStyle  = kCFDateFormatterShortStyle,//“11/23/37” or “3:30pm”
    NSDateFormatterMediumStyle = kCFDateFormatterMediumStyle,//\"Nov 23, 1937\"
    NSDateFormatterLongStyle   = kCFDateFormatterLongStyle,//\"November 23, 1937” or “3:30:32pm\"
    NSDateFormatterFullStyle   = kCFDateFormatterFullStyle//“Tuesday, April 12, 1952 AD” or “3:30:42pm PST”
} NSDateFormatterStyle;
复制代码

 

可计算和所给时间和当天时间的差距
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
NSCalendar *calendar = [NSCalendar currentCalendar]; //日历
     NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date toDate:[NSDate date] options:0];
     int  year = [components year];
     int  month = [components month];
     int  day = [components day];
     //三天以内更改显示格式
     if  (year == 0 && month == 0 && day < 3) {
         if  (day == 0) {
             title = NSLocalizedString(@ "今天" ,nil);
         else  if  (day == 1) {
             title = NSLocalizedString(@ "昨天" ,nil);
         else  if  (day == 2) {
             title = NSLocalizedString(@ "前天" ,nil);
         }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值