如何计算Objective-C中特定日期的一年中的哪一天?

问题描述 投票:24回答:5

这是我发现自己花了几个小时才弄明白并因此想与你分享的事情。

问题是:如何确定特定日期的一年中的哪一天?

例如1月15日是第15天,12月31日是不是闰年的第365天。

iphone objective-c nsdate nsdateformatter
5个回答
73
投票

试试这个:

NSCalendar *gregorian =
   [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger dayOfYear =
   [gregorian ordinalityOfUnit:NSDayCalendarUnit
     inUnit:NSYearCalendarUnit forDate:[NSDate date]];
[gregorian release];
return dayOfYear;

其中date是您想要确定一年中某一天的日期。 NSCalendar.ordinalityOfUnit方法的文档是here


6
投票

因此,我提出的解决方案非常简洁,并没有任何复杂的问题。

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"D"];
NSUInteger dayOfYear = [[formatter stringFromDate:[NSDate date]] intValue];
[formatter release];
return dayOfYear;

我花了这么长时间才弄清楚的诀窍是使用NSDateFormatter。 “D”是一年中的标志。

希望这对你有同样问题的人有所帮助。


4
投票

使用ARC并替换弃用的符号,John Feminella的答案如下:

NSCalendar *greg    = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
NSUInteger dayOfYear= [greg ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitYear forDate:[NSDate date]];

0
投票

Swift 4变种:

let date = Date() // now
let calendar = Calendar(identifier: .gregorian)
let dayOfYear = calendar.ordinality(of: .day, in: .year, for: Date()) 

-2
投票

随着NSDate类。使用消息timeIntervalSinceDate。它将返回一个NSTimeInterval值(实际上它是一个双精度值),表示自您想要的日期以来经过的秒数。在那之后,很容易转换为秒。

如果你截断seconds/86400会给你几天。

假设您想要自2010年1月1日起的日子。

// current date/time
NSDate *now = [[NSData alloc] init]; 

// seconds elapsed since January 1st 2010 00:00:00 (GMT -4) until now
NSInteval interval = [now timeIntervalSinceDate: [NSDate dateWithString:@"2010-01-01 00:00:00 -0400"]];

// days since January 1st 2010 00:00:00 (GMT -4) until now
int days = (int)interval/86400;
© www.soinside.com 2019 - 2024. All rights reserved.