我想查找今天的當天日期是當前年份。如果今天是2012年3月15日,我應該得到75(31 + 29 + 15)。或者我們可以簡單地說今天到今年1月1日之間的天數。 有人可以幫我嗎?ios中的當前日期數
問候
潘卡
我想查找今天的當天日期是當前年份。如果今天是2012年3月15日,我應該得到75(31 + 29 + 15)。或者我們可以簡單地說今天到今年1月1日之間的天數。 有人可以幫我嗎?ios中的當前日期數
問候
潘卡
使用NSCalendar的ordinalityOfUnit方法來獲取全年天數 - 指定NSDayCalendarUnit inUnit:NSYearCalendarUnit
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDate *today = [NSDate date];
NSInteger dc = [currentCalendar ordinalityOfUnit:NSDayCalendarUnit
inUnit:NSYearCalendarUnit
forDate:today];
給269 2012年9月25日
使用NSDateComponents
你可以可以收集NSDayCalendarUnit
分量應該表示年份的當天。
東西沿着以下的線路應滿足您的需求:
//create calendar
NSCalendar *calendar = [NSCalendar currentCalendar];
//set calendar time zone
[calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
//gather date components
NSDateComponents *components = [calendar components:NSDayCalendarUnit fromDate:[NSDate date]];
//gather time components
NSInteger day = [components day];
正確的做法,但你的代碼會給一天的數量當月,而不是在一年 – Vladimir
哦?我很抱歉。關於NSDayCalendarUnit組件的Apple文檔不是很清楚。 – CaptainRedmuff
按照data format reference,您可以使用D
符代表一年中的一天。如果您想執行一些計算,日期格式化程序並不是那麼有用,但如果您只是想顯示一年中的某一天,則可能是最簡單的方法。該代碼看起來是這樣的:
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setCalendar:cal];
[df setDateFormat:@"DDD"]; // D specifier used for day of year
NSString *dayOfYearString = [df stringFromDate:someDate]; // you choose 'someDate'
NSLog(@"The day is: %@", dayOfYearString);
使用NSDate
,NSDateComponents
和NSCalendar
類,你可以很容易地計算比上年今天的最後一天之間的天量(這是與我們在計算今天的本年度號):
// create your NSDate and NSCalendar objects
NSDate *today = [NSDate date];
NSDate *referenceDate;
NSCalendar *calendar = [NSCalendar currentCalendar];
// get today's date components
NSDateComponents *components = [calendar components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:today];
// changing the date components to the 31nd of December of last year
components.day = 31;
components.month = 12;
components.year--;
// store these components in your date object
referenceDate = [calendar dateFromComponents:components];
// get the number of days from that date until today
components = [calendar components:NSDayCalendarUnit fromDate:referenceDate toDate:[NSDate date] options:0];
NSInteger days = components.day;
這就是**答案! – Vladimir