从 NSCalendar 获取一个月的第一天 [英] Get first day in a month from NSCalendar

查看:20
本文介绍了从 NSCalendar 获取一个月的第一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法的这个子集,需要获取当前月份的第一天.

I have this subset of a method that needs to get day one of the current month.

NSDate *today = [NSDate date];  // returns correctly 28 february 2013
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = 1;
NSDate *dayOneInCurrentMonth = [gregorian dateByAddingComponents:components toDate:today options:0];

dayOneInCurrentMonth 然后打印出 2013-03-01 09:53:49 +0000,即下个月的第一天.

dayOneInCurrentMonth then prints out 2013-03-01 09:53:49 +0000, the first day of the next month.

如何获得当月的第一天?

How do I get day one of the current month?

推荐答案

你的逻辑是错误的:你没有将日期的天数设置为 1,而是在当前日期上添加了一天.

Your logic is wrong: Instead of setting the date's day to 1, you're adding a day to the current date.

试试这样的:

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *components = [gregorian components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit) fromDate:today];
components.day = 1;

NSDate *dayOneInCurrentMonth = [gregorian dateFromComponents:components];

这篇关于从 NSCalendar 获取一个月的第一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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