我想查找今天的当天日期是当前年份。如果今天是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