NSDate, NSDateFormatter的使用

来源:互联网 发布:黄金看盘软件 编辑:程序博客网 时间:2024/05/16 11:32

        //NSDate
        
//创建对象
        
//通过NSDate创建的对象获取的是0时区的时间

        NSDate * date = [NSDate date];
        
NSLog(@"%@"
, date);
        
//获取明日此时的时间
        
NSDate * tomorrow = [NSDate dateWithTimeIntervalSinceNow:24 * 60 * 60];
        
NSLog(@"%@"
, tomorrow);
        
//获取昨天此时的时间
        
NSDate * yesterday = [NSDate dateWithTimeIntervalSinceNow: - 24 * 60 * 60];
         
NSLog(@"%@", yes
terday);

        // 获取两个时间的时间间隔
        
NSDate * nowDate = [NSDate date];
        
NSDate * tomorrowDate = [NSDate dateWithTimeIntervalSinceNow:24 * 60 * 60];
        
NSTimeInterval timeInterval = [nowDate timeIntervalSinceDate:tomorrowDate];
        NSLog(@"%.2f", timeInterval);
             //比较日期的早晚
        NSDate * date2 = [nowDate earlierDate:tomorrowDate];
        
NSDate * date3 = [nowDate laterDate:tomorrowDate];
        
NSLog(@"earlierDate = %@", date2);
        
NSLog(@"laterDate = %@", date3);
        
//判断日期是否相等
        
BOOL isEqual = [nowDate isEqualTo:tomorrowDate];
        
if (isEqual) {
            
NSLog(@"yes");
        }
else{
            
NSLog(@"no");
        }
    }


//NSDateFormatter
    //1.按照指定的日期格式NSData对象 转为字符串
    
NSDate * date = [NSDate date];
    
NSDateFormatter * formatter1 = [[NSDateFormatter allocinit
];
    
//设置转换格式
    
//HH表示24小时制, hh表示12小时制
    
//DD表示365天制小写dd表示月制
    
//EE周几, aa下午
 
   [formatter1 setDateFormat:@"MMdd EE aahh:mm "];
    
//转换成字符串
    
NSString * str = [formatter1 stringFromDate:date];
    
NSLog(@"str =%@"
, str);
    

    
//2.按照指定的日期格式将日期字符串 转为NSData对象
    
NSString * str1 = @"20141230 15112";
    
NSDateFormatter * formatter2 = [[NSDateFormatter allocinit];
    [formatter2 
setDateFormat:@"yyyyMMdd HHmmss"
];
    
//对于NADate对象来说获取到的永远是0时区的时间;
    
NSDate * date2 = [formatter2 dateFromString:str1];
    
NSLog(@"date2 = %@", date2);

0 0
原创粉丝点击