Work with NSCalendar - getting the next first day of the month

It's a little weird, but is it possible to use NSCalendar (or any component, for that matter) to figure out what date the next “first day of the month” will be?

For example, today is Thursday, March 25, 2010. The next "first day of the month" will be April 6th. Similarly, if I were looking for the next “first Tuesday of the month” on April 1, it would still be April 6th.

How do you do this?

Thank you so much!!!!!

+3
source share
2 answers

/. MacRuby, , , Objective-C, ( MacRuby ):

dc = NSDateComponents.alloc.init
# Set month to April 2010
dc.setYear 2010
dc.setMonth 4

dc.setWeekday 3 # 1 = Sunday, 2 = Monday, ...
dc.setWeekdayOrdinal 1 # We want the first weekday of the month

cal = NSCalendar.alloc.initWithCalendarIdentifier NSGregorianCalendar
date = cal.dateFromComponents dc
date.description # => "2010-04-06 00:00:00 +0200"

, " " : , , . -[NSCalendar components:fromDate:], / NSDate.

+4

, , :

NSDateComponents *components = [[NSDateComponents alloc] init];
[components setWeekday:2]; // Monday
[components setMonth:5]; // May
[components setYear:2008];
[components setWeekdayOrdinal:1]
NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:components];

See this manual for examples and details.

+1
source

Source: https://habr.com/ru/post/1738498/


All Articles