これは非常に単純な概念ですが、今のところ、エレガントな(そしてカレンダーのロケールに依存しない)ソリューションを見つけることができませんでした。任意のNSDate
の月の最初の日を見つける必要があります。たとえば、任意のNSDate
(arbitraryDate
)が与えられると、firstDayOfMonthDate
の月の最初の日を表す別のNSDateオブジェクトが返されます(これをarbitraryDate
と呼びましょう)。月の最初の日にNSDateオブジェクトが必要なだけなので、時間コンポーネントは重要ではありません(ただし、時間をゼロにするだけで便利です)。
助けてくれてありがとう。
考えられる解決策:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *arbitraryDate = [NSDate date];
NSDateComponents *comp = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:arbitraryDate];
[comp setDay:1];
NSDate *firstDayOfMonthDate = [gregorian dateFromComponents:comp];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear
fromDate:[NSDate date]];
components.day = 1;
NSDate *firstDayOfMonthDate = [[NSCalendar currentCalendar] dateFromComponents: components];
NSLog(@"First day of month: %@", [firstDayOfMonthDate descriptionWithLocale:[NSLocale currentLocale]]);
Swift
誰かに役立つ場合に備えて、月末日を取得することを含めました。
extension Date {
func lastDayOfMonth() -> Date {
let calendar = Calendar.current
let dayRange = calendar.range(of: .day, in: .month, for: self)
let dayCount = dayRange!.count
var comp = calendar.dateComponents([.year, .month, .day], from: self)
comp.day = dayCount
return calendar.date(from: comp)!
}
func firstDayOfMonth() -> Date {
let calendar: Calendar = Calendar.current
var components: DateComponents = calendar.dateComponents([.year, .month, .day], from: self)
components.setValue(1, for: .day)
return calendar.date(from: components)!
}
}
スウィフト3:
let calendar = Calendar.current
var comps = calendar.dateComponents([.year, .month], from: date)
comps.setValue(1, for: .day)
let firstDayOfMonth = calendar.date(from: comps)!
// I tried this, but it doesn't work, why?
// let firstDayOfMonth = calendar.date(bySetting: .day, value: 1, of: date)!
Swiftバージョン
let arbitraryDate:NSDate = NSDate()
let calendar:NSCalendar = NSCalendar.currentCalendar()
let components:NSDateComponents = calendar.components([.Year, .Month, .Day], fromDate: arbitraryDate)
components.setValue(1, forComponent: .Day)
let firstDayOfMonthDate = calendar.dateFromComponents(components)