web-dev-qa-db-ja.com

月の最初の日付、最後の日付を取得しますか?

最初の日付、最後の日付を取得したい、試してみる

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;

log: 2012,5,1

Lastdate od monthを取得するにはどうすればよいですか?

アドバイスをお願いします、ありがとう!

17
Alice Chen

私が書いたいくつかのNSDateカテゴリメソッドはあなたを助けます:

月の始まりを見つける簡単な方法は次のとおりです。

 (NSDate *) startOfMonth
{
    NSCalendar * calendar = [NSCalendar currentCalendar];

    NSDateComponents * currentDateComponents = [calendar components: NSYearCalendarUnit | NSMonthCalendarUnit fromDate: self];
    NSDate * startOfMonth = [calendar dateFromComponents: currentDateComponents];

    return startOfMonth;
}

現在の日から年と月のコンポーネントを取得し、再び日付に変換するだけです。

月末には、いくつかの方法を使用します。

- (NSDate *) dateByAddingMonths: (NSInteger) monthsToAdd
{
    NSCalendar * calendar = [NSCalendar currentCalendar];

    NSDateComponents * months = [[NSDateComponents alloc] init];
    [months setMonth: monthsToAdd];

    return [calendar dateByAddingComponents: months toDate: self options: 0];
}

そして

- (NSDate *) endOfMonth
{
    NSCalendar * calendar = [NSCalendar currentCalendar];

    NSDate * plusOneMonthDate = [self dateByAddingMonths: 1];
    NSDateComponents * plusOneMonthDateComponents = [calendar components: NSYearCalendarUnit | NSMonthCalendarUnit fromDate: plusOneMonthDate];
    NSDate * endOfMonth = [[calendar dateFromComponents: plusOneMonthDateComponents] dateByAddingTimeInterval: -1]; // One second before the start of next month

    return endOfMonth;
}

これは3ステップのプロセスです。現在の日付に1か月を追加し、次の月の始まりを見つけてから、1秒を引いて今月末を見つけます。


Swift

extension Date {

    func startOfMonth() -> Date? {

        let calendar = Calendar.current
        let currentDateComponents = calendar.dateComponents([.year, .month], from: self)
        let startOfMonth = calendar.date(from: currentDateComponents)

        return startOfMonth
    }

    func dateByAddingMonths(_ monthsToAdd: Int) -> Date? {

        let calendar = Calendar.current
        var months = DateComponents()
        months.month = monthsToAdd

        return calendar.date(byAdding: months, to: self)
    }

    func endOfMonth() -> Date? {

        guard let plusOneMonthDate = dateByAddingMonths(1) else { return nil }

        let calendar = Calendar.current
        let plusOneMonthDateComponents = calendar.dateComponents([.year, .month], from: plusOneMonthDate)
        let endOfMonth = calendar.date(from: plusOneMonthDateComponents)?.addingTimeInterval(-1)

        return endOfMonth

    }
}

スウィフト2

extension NSDate {

    func startOfMonth() -> NSDate? {

        let calendar = NSCalendar.currentCalendar()
        let currentDateComponents = calendar.components(.CalendarUnitYear | .CalendarUnitMonth, fromDate: self)
        let startOfMonth = calendar.dateFromComponents(currentDateComponents)

        return startOfMonth
    }

    func dateByAddingMonths(monthsToAdd: Int) -> NSDate? {

        let calendar = NSCalendar.currentCalendar()
        let months = NSDateComponents()
        months.month = monthsToAdd

        return calendar.dateByAddingComponents(months, toDate: self, options: nil)
    }

    func endOfMonth() -> NSDate? {

        let calendar = NSCalendar.currentCalendar()
        if let plusOneMonthDate = dateByAddingMonths(1) {
            let plusOneMonthDateComponents = calendar.components(.CalendarUnitYear | .CalendarUnitMonth, fromDate: plusOneMonthDate)

            let endOfMonth = calendar.dateFromComponents(plusOneMonthDateComponents)?.dateByAddingTimeInterval(-1)

            return endOfMonth
        }

        return nil
    }
}
28
Ashley Mills

このトリックを試してください。

Day Param:1は今月の最初の日付を取得することです

Day Param:0は、翌月の前の月の最終日を取得することにより、今月の最終日を取得することです(今月を意味します))

- (void)returnDate:(NSDate *)date {

    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];

    NSDate * firstDateOfMonth = [self returnDateForMonth:comps.month year:comps.year day:1];
    NSDate * lastDateOfMonth = [self returnDateForMonth:comps.month+1 year:comps.year day:0];

    NSLog(@"date %@", date);              // date 2013-06-20
    NSLog(@"First %@", firstDateOfMonth); // firstDateOfMonth 2013-06-01
    NSLog(@"Last %@", lastDateOfMonth);   // lastDateOfMonth  2013-06-30

}

- (NSDate *)returnDateForMonth:(NSInteger)month year:(NSInteger)year day:(NSInteger)day {

    NSDateComponents *components = [[NSDateComponents alloc] init];

    [components setDay:day];
    [components setMonth:month];
    [components setYear:year];

    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    return [gregorian dateFromComponents:components];
}

正しい日付フォーマッターを忘れないでください

IOS 8.0用に更新

- (void)returnDate:(NSDate *)date { 
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];

    NSDate * firstDateOfMonth = [self returnDateForMonth:comps.month year:comps.year day:1];
    NSDate * lastDateOfMonth = [self returnDateForMonth:comps.month+1 year:comps.year day:0];

    NSLog(@"date %@", date);              // date 2013-06-20
    NSLog(@"First %@", firstDateOfMonth); // firstDateOfMonth 2013-06-01
    NSLog(@"Last %@", lastDateOfMonth);   // lastDateOfMonth  2013-06-30

}

- (NSDate *)returnDateForMonth:(NSInteger)month year:(NSInteger)year day:(NSInteger)day {

    NSDateComponents *components = [[NSDateComponents alloc] init];

    [components setDay:day];
    [components setMonth:month];
    [components setYear:year];

    NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    return [gregorian dateFromComponents:components];
}

今あなたは一緒に働いています:

  • NSCalendarUnitYear
  • NSCalendarUnitWeekOfMonth
  • NSCalendarIdentifierGregorian
7
Nazir

さて、私は自分のカレンダーコントロールをローリングしているので、先に進んでNSCalendarカテゴリを作成しました。これが私のlastOfMonthメソッドです。

- (NSDate *)lastOfMonth:(NSDate *)date
{
    NSDateComponents *dc = [self components:NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit fromDate:date];

    NSRange dim = [self rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
    dc.day = dim.length;

    return [self dateFromComponents:dc];
}
3
Scott Means

Swift 2.の場合、今月の最初の日を取得するには:

    let date = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let dateComponents = calendar.components([NSCalendarUnit.Month, NSCalendarUnit.Year], fromDate: date)
    let firstDay = self.returnDateForMonth(dateComponents.month, year: dateComponents.year, day: 1)
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd-MMM-yy"

    print("First day of this month: \(firstDay)") // 01-Sep-15

そしてこれを行う関数:

 func returnDateForMonth(month:NSInteger, year:NSInteger, day:NSInteger)->NSDate{
    let comp = NSDateComponents()
    comp.month = month
    comp.year = year
    comp.day = day

    let grego = NSCalendar.currentCalendar()
    return grego.dateFromComponents(comp)!
}
2
Dasoga

あなたは使用して月の最後の日付を得ることができます:-

NSDate currDate=[NSDate date];

-(NSString *)getLastDateMonth:(NSDate *)currDate{

  NSCalendar *gregCalendar=[[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

  NSDateComponents *components=[gregCalendar components:NSMonthCalendarUnit|NSYearCalendarUnit fromDate:currDate];
  NSInteger month=[components month];
  NSInteger year=[components year];

  if (month==12) {
    [components setYear:year+1];
    [components setMonth:1];
  } else {
    [components setMonth:month+1];
  }
  [components setDay:1];

  NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
  [dateFormat setDateStyle:NSDateFormatterShortStyle];
  NSString *lastDateOfMonth = [dateFormat stringFromDate:(NSDate *)[[gregCalendar dateFromComponents:components] dateByAddingTimeInterval:-86400]];
  dateFormat=nil;
  return lastDateOfMonth;
}
1
Abhishek Singh

Swift Nazirの回答に基づく

        func getFirstAndLastDateOfMonth(date: NSDate) -> (fistDateOfMonth: NSDate, lastDateOfMonth: NSDate) {

            let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
            let calendarUnits = NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth
            let dateComponents = calendar?.components(calendarUnits, fromDate: date)

            let fistDateOfMonth = self.returnedDateForMonth(dateComponents!.month, year: dateComponents!.year, day: 1)
            let lastDateOfMonth = self.returnedDateForMonth(dateComponents!.month + 1, year: dateComponents!.year, day: 0)

            println("fistDateOfMonth \(fistDateOfMonth)")
            println("lastDateOfMonth \(lastDateOfMonth)")

            return (fistDateOfMonth!,lastDateOfMonth!)
        }

       func returnedDateForMonth(month: NSInteger, year: NSInteger, day: NSInteger) -> NSDate? {
            var components = NSDateComponents()
            components.day = day
            components.month = month
            components.year = year

            let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)

            return gregorian!.dateFromComponents(components)
        }
1
jose920405

トリックやハックの必要はないようです、NSCalendarrangeOfUnit仕事はかなりうまくいきます:

NSCalendar *cal = [NSCalendar currentCalendar];

NSDateComponents *dc = [[NSDateComponents alloc] init];
dc.year = 1947;
dc.month = 8; //desired month

//calculate start date
dc.day = 1; //As far as I can think start date of a month will always be 1
NSDate *start = [cal dateFromComponents:dc];

//calculate last date of month
NSRange dim = [cal rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:start]; // we used start date as it has the same month & year value as desired
dc.day=dim.length; //this is the simply the last day of the desired month
NSDate *last = [[NSCalendar currentCalendar] dateFromComponents:dc];

検証のために値をログに記録します。

NSLog(@"Start day of month Date: %@", start);
NSLog(@"Last day of month Date: %@", last);

NSCalendar rangeOfUnitに関するAppleのドキュメント: https://developer.Apple.com/documentation/foundation/nscalendar/1418344-rangeofunit

p.sは、@ Scott Meansの回答と同じロジックを使用しているように見えますが、カテゴリは必要ないため、好きな回答を使用してください。

0

Swift5が月末を迎える-さまざまな情報源に基づく

// -------------------------------------------------------
// lastDayOfMonth
// -------------------------------------------------------
static func lastDayOfMonth(year:Int, month:Int) -> Int {
    let calendar:Calendar = Calendar.current
    var dc:DateComponents = DateComponents()
    dc.year = year
    dc.month = month + 1
    dc.day = 0
    let lastDateOfMonth:Date = calendar.date(from:dc)!
    let lastDay = calendar.component(Calendar.Component.day, from: lastDateOfMonth)
    return lastDay
}
0
Totte Alm