iphone - iOS 中当年的天数

标签 iphone ios nsdate

我想找到今天在当年的天数。例如,如果今天是 2012 年 3 月 15 日,我应该得到 75(31 + 29 + 15)。或者我们可以简单地说从今天到当年 1 月 1 日之间的天数。

最佳答案

使用 NSCalendarordinalityOfUnit 方法获取一年中的第几天 - 在 Unit:NSYearCalendarUnit 中指定 NSDayCalendarUnit

swift

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

关于iphone - iOS 中当年的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12584286/

相关文章:

iphone - iOS 开发 : Can I store an array of integers in a Core Data object without creating a new table to represent the array?

iphone - 带有 pushViewController 动画的 popViewController

ios - UITableViewCell 的 UIImage 的内存在 segue 后退按钮后未释放

iphone - 如何使用 Core plot 沿 X 轴绘制 NSDate

ios - 更改日期较早的单元格的背景颜色

ios - 什么是新 iPhone 的透视和流行力量?

iphone - MKAnnotationView 图像属性

iphone - 如何将图标添加到 iphone/ipod 状态栏?

ios - UIScrollView 中仅水平缩放 UIView

objective-c - 在 Objective C 中将公历日期转换为儒略日计数