我想找出今天是当年的天数。例如,如果今天是 2012 年 3 月 15 日,我应该得到 75(31 + 29 + 15)。或者我们可以简单地说今天和当年 Jan01 之间的天数。
问问题
2407 次
4 回答
13
使用 的ordinalityOfUnit
方法NSCalendar
获取一年中的天数 - 指定NSDayCalendarUnit inUnit:NSYearCalendarUnit
迅速
let calendar: Calendar = .autoupdatingCurrent
let dayOfTheYear = calendar.ordinality(of: .day, in: .year, for: Date())
Objective-C
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDate *today = [NSDate date];
NSInteger dc = [currentCalendar
ordinalityOfUnit:NSDayCalendarUnit
inUnit:NSYearCalendarUnit
forDate:today
];
2012 年 9 月 25 日为 269
于 2012-09-25T14:57:37.697 回答
2
使用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];
于 2012-09-25T13:51:34.730 回答
1
根据数据格式参考,可以使用说明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);
于 2012-09-25T14:20:52.893 回答
0
使用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;
于 2012-09-25T14:32:11.620 回答