LoginSignup
11
11

More than 5 years have passed since last update.

月末の計算

Posted at

NSDateから月末を取得する関数を作ってみました。

func endOfMonth(date:NSDate) -> NSDate
{
    let cal = NSCalendar.currentCalendar()
    let flags : NSCalendarUnit = [.Year, .Month, .Day]
    let comps : NSDateComponents = cal.components(flags , fromDate: date)

    var y = comps.year
    var m = comps.month
    m = m + 1
    if (m >= 13) {
        y = y + 1
        m = 1
    }

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd";

    let firstOfMonth : NSDate = dateFormatter.dateFromString("\(y)-\(m)-01")!

    let endOfMonth : NSDate = firstOfMonth.dateByAddingTimeInterval(-60*60*24)

    return endOfMonth
}

使い方

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd";
let testDate = dateFormatter.dateFromString("2014-2-1")!;
let resOut = endOfMonth(testDate) // "Feb 28, 2014, 12:00 AM"
11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11