如何以编程方式在iphone中获取当前年份的第一个日期

时间:2013-12-07 05:21:50

标签: iphone ios7

我在iphone应用程序中工作,现在我想从当前日期获取当前年度和当前月份的第一个日期。      For(e.x:年度第一次:2013/01/01)     并且(e.x月份的第一个日期是:2013/12/01)

请帮我解决这个问题。感谢。

2 个答案:

答案 0 :(得分:4)

// This is your currentDate
NSDate *today = [NSDate date];

// NSDateFormatter to separate the Year and Month from currentDate
NSDateFormatter *df = [[NSDateFormatter alloc] init]
[df setDateFormat:@"yyyy"];

NSInteger currentYear = [[df stringFromDate:today] integerValue];
NSString *currentYearFirstDate = [NSString stringWithFormat:@"%d/01/01", currentYear];

[df setDateFormat:@"MM"];
NSInteger currentMonth = [[df stringFromDate:today] integerValue];
NSString *currentMonthFirstDate = [NSString stringWithFormat:@"%d/%d/01", currentYear, currentMonth];

// You can get date object from above string via using below date format
[df setDateFormat:@"yyyy/MM/dd"];

答案 1 :(得分:2)

NSDateComponents *components = [calendar components:units fromDate:[NSDate date]];
[components setDay:1];
self.currentDate = [calendar dateFromComponents:components];
int m = components.month;
int y = components.year;
int d = components.day;

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy MM dd"];
NSDate *firstDateOfMonth = [df dateFromString:[NSString stringWithFormat:@"%d %d 01",y,m]];
NSDate *firstDateOfYear = [df dateFromString:[NSString stringWithFormat:@"%d 01 01",y]];