如何在Objective c中获取当月的日期? [英] How to get dates of current month in Objective c?

查看:101
本文介绍了如何在Objective c中获取当月的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个使用日期,月份,年份的应用程序。我想要当前的月份日期,因为当前月份可以有28,29,30,31天。我试图获得当年的月份。但我不知道上面的代码。这是我的代码。

I am developing a app which uses the date, month, year. I want the current month dates,because current month can have 28,29,30,31 days. I have tried to get current year months. but i don't know the code for above. here is my code.

  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate           *today           = [NSDate date];
NSCalendar       *currentCalendar = [NSCalendar currentCalendar];
NSDateComponents *yearComponents  = [currentCalendar components:NSYearCalendarUnit  fromDate:today];
int currentYear  = [yearComponents year];
for(int months = 0; months < 12; months++)
{
    NSString *monthName = [NSString stringWithFormat:@"%@ %i",[[dateFormatter monthSymbols]objectAtIndex: months],currentYear];
    NSLog(@"%@ %i",[[dateFormatter monthSymbols]objectAtIndex: months],currentYear);
    [monthArray addObject:monthName];
}


推荐答案

为了得到一天,你可以NSDateComponents

To get day you can you NSDateComponents

NSDate *date = [NSDate date];
NSCalendar *gregorian = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit) fromDate:date];
NSInteger day = [dateComponents day];

您可以根据需要添加更多组件单位: NSMonthCalendarUnit,NSWeekdayCalendarUnit, NSYearCalendarUnit

You can add more component units as you need like :NSMonthCalendarUnit,NSWeekdayCalendarUnit,NSYearCalendarUnit

这篇关于如何在Objective c中获取当月的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆