1 //當前時間建立nsdate
nsdate *mydate = [nsdate date];//很重要
nslog(@"mydate = %@",mydate);
2 //從現在開始的24小時
nstimeinterval secondsperday = 24*60*60;
nsdate *tomorrow = [nsdate datewithtimeintervalsincenow:secondsperday];
nslog(@"mydate = %@",tomorrow);
3//根據已有日期建立日期
nstimeinterval secondsperday1 = 24*60*60;
nsdate *now = [nsdate date];
nsdate *yesterday = [now addtimeinterval:-secondsperday1];
nslog(@"yesterday = %@",yesterday);
4//比較日期
bool samedate = [now isequaltodate:yesterday];//重要
nslog(@"samedate = %lu",samedate);
4.1//獲取
較早的日期
nsdate *earlierdate = [yesterday earlierdate:now];
nslog(@"earlierdate = %@",earlierdate);
4.2//較晚的日期
nsdate *laterdate = [yesterday laterdate:now];
nslog(@"laterdate = %@",laterdate);
//兩個日期之間相隔多少秒//重要
nstimeinterval secondsbetweendates= [yesterday timeintervalsincedate:now];
nslog(@"secondsbetweendates= %lf",secondsbetweendates);
//通過nscalendar類來建立日期
nsdatecomponents *comp = [[nsdatecomponentsalloc]init];
[comp setmonth:06];
[comp setday:01];
[comp setyear:2001];
nscalendar *mycal = [[nscalendaralloc]initwithcalendaridentifier:nsgregoriancalendar];
nsdate *mydate1 = [mycal datefromcomponents:comp];
nslog(@"mydate1 = %@",mydate1);
//從已有日期獲取日期
unsigned units = nsmonthcalendarunit|nsdaycalendarunit|nsyearcalendarunit;
nsdatecomponents *comp1 = [mycal components:units fromdate:now];
nsinteger month = [comp1 month];
nsinteger year = [comp1 year];
nsinteger day = [comp1 day];
//nsdateformatter實現日期的輸出
nsdateformatter *formatter = [[nsdateformatteralloc]init];
[formatter setdatestyle:nsdateformatterfullstyle];//直接輸出的話是機器碼
//或者是手動設定樣式[formatter setdateformat:@"yyyy-mm-dd"];
nsstring *string = [formatter stringfromdate:now];
nslog(@"string = %@",string);
nslog(@"formater = %@",formatter);
轉nsdate
nsstring *timestr = @"06:45";
nsdateformatter
*dateformatter = [[nsdateformatter alloc] init] ;
[dateformatter setdateformat:@"hh:mm"];
nsdate *time = [dateformatter
datefromstring
:timestr];
NSDate基本用法
nsdate常用 範例 nsdate類用於儲存時間值,同時提供了一些方法來處理一些基於秒級別時差 time interval 運算和日期之間的早晚比較等。1.建立或初始化可用以下方法 用於建立nsdate例項的類方法有 id date 返回當前時間 id datewithtimeintervalsi...
NSDate 使用總結
1 當前時間建立nsdate nsdate mydate nsdate date nslog mydate mydate 2 從現在開始的24小時 nstimeinterval secondsperday 24 60 60 nsdate tomorrow nsdate datewithtimeint...
NSDate初步使用
nsdate 的常用用法 1.建立或初始化可用以下方法 用於建立 nsdate 例項的類方法有 id date 返回當前時間 id datewithtimeintervalsincenow nstimeinterval secs 返回以當前時間為基準,然後過了 secs 秒的時間 id datewi...