5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Swift] NSDateで月末月初めを計算する

Last updated at Posted at 2016-07-06

はじめに

調べたところObjective-Cの情報ばかりだったのでSwift版を共有しようと思います。

こちらが元記事です。
NSDateで月末月初 ※ただしGMTに注意

コード

// dateの月の月末月初めを計算します。
let date = NSDate()

let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
// 年月日時分秒のNSComponentsを作る(この時点ではdateと一致したものになっている)
let comp = calendar.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: date)

// ここで1日の0時0分0秒に設定します
comp.day = 1
comp.hour = 0
comp.minute = 0
comp.second = 0

// NSComponentsをNSDateに変換します
let monthBeginningDate = calendar.dateFromComponents(comp)

// その月が何日あるかを計算します
let range = calendar.rangeOfUnit(.Day, inUnit: .Month, forDate: date)
let lastDay = range.length

// ここで月末に日を変えます
comp.day = lastDay

let monthEndDate = calendar.dateFromComponents(comp)
5
8
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
5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?