NSDate 基本用法

来源:互联网 发布:数据库安全防护 编辑:程序博客网 时间:2024/04/28 22:55

#import <Foundation/Foundation.h>


int main(int argc,constchar * argv[])

{


    @autoreleasepool

    {

       //创建时间对象

       NSDate *nowdate=[NSDatedate];

       //打印的是0时区的时间,北京(东-8

       NSLog(@"%@",nowdate);

       //创建一定间隔时间的对象,NSTimeInterval的默认单位是秒,当前对象设置的是1

       NSTimeInterval timeinterval=24*60*60;

        nowdate=[NSDatedateWithTimeIntervalSinceNow:timeinterval];

       NSLog(@"%@",nowdate);

        nowdate=[NSDatedateWithTimeIntervalSinceNow:-timeinterval];

       NSLog(@"%@",nowdate);

        

        //时间转换成字符串

        

        // 日期格式化类

       NSDateFormatter *dateformatter=[[NSDateFormatteralloc]init];

        // y   M   d

        // m s   H 24)时  h12)时

                 //   e 周    a 上午或下午

        [dateformattersetDateFormat:@"yyyy-MM-dd eee HH:mm:ss aaaa"];

        [dateformattersetAMSymbol:@"上午"];

        [dateformatter setPMSymbol:@"下午"];


        //[dateformatter setDateStyle:NSDateFormatterFullStyle];

       NSString *strDate=[dateformatterstringFromDate:[NSDatedate]];

       NSLog(@"%@",strDate);

        

        //字符串转换成时间

        NSString *string=@"2013-12-7 21:23:50";

       NSDate *date=[dateformatterdateFromString:string];

       NSLog(@"%@",date);

        

       //获取日期各个部分整数值

       NSDate *now=[NSDatedate];

       //

        NSInteger nowyear=[[nowdateWithCalendarFormat:niltimeZone:nil]yearOfCommonEra];

       NSLog(@"%ld",(long)nowyear);

       //

        NSInteger nowmonth=[[nowdateWithCalendarFormat:niltimeZone:nil]monthOfYear];

       NSLog(@"%ld",nowmonth);

       //

        NSInteger nowday=[[nowdateWithCalendarFormat:niltimeZone:nil]dayOfMonth];

       NSLog(@"%ld",nowday);

       //

        NSInteger nowhour=[[nowdateWithCalendarFormat:niltimeZone:nil]hourOfDay];

       NSLog(@"%ld",nowhour);

       //

        NSInteger nowmin=[[nowdateWithCalendarFormat:niltimeZone:nil]minuteOfHour];

       NSLog(@"%ld",nowmin);

       //

        NSInteger nowsec=[[nowdateWithCalendarFormat:niltimeZone:nil]secondOfMinute];

       NSLog(@"%ld",nowsec);

       //周几

        NSInteger nowweek=[[nowdateWithCalendarFormat:niltimeZone:nil]dayOfWeek];

       NSLog(@"%ld",nowweek);

        

    }

   return0;

}


原创粉丝点击