iOSの日付計算でよく使うオレオレメソッドをまとめてみる

iOSの日付周りの計算でよく使うメソッドをまとめてみた。随時更新予定です。

該当月の開始日と終了日を返す


    func getStartDateAndEndDate(year:Int,month:Int) -> (NSDate,NSDate) {
        
        var calendar:NSCalendar = NSCalendar.currentCalendar()
        calendar.timeZone = NSTimeZone.localTimeZone()
                        
        var components:NSDateComponents = calendar.components(
            NSCalendarUnit.EraCalendarUnit | NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.MonthCalendarUnit
                | NSCalendarUnit.DayCalendarUnit | NSCalendarUnit.HourCalendarUnit
            , fromDate: NSDate())
                
        components.year = year
        components.month = month
        components.day = 1
        components.hour = 0
                
        var startDate:NSDate = calendar.dateFromComponents(components) as NSDate!
        var endDate:NSDate = startDate.lastDayOfTheMonth()
        
        return (startDate,endDate)
   }

   func lastDayOfTheMonth() -> NSDate {
        var calendar:NSCalendar = NSCalendar.currentCalendar()
        var components:NSDateComponents = calendar.components(NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.WeekCalendarUnit  | NSCalendarUnit.WeekCalendarUnit,  fromDate: self)
        
        components.month = components.month + 1
        components.day = 0
        
        let _lastDay:NSDate = calendar.dateFromComponents(components) as NSDate!
        return _lastDay

    }

タイムゾーンに準じた現在の日付を返す

 func localDate() -> NSDate {
        var date:NSDate = NSDate()
                
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy/MM/dd HH:mm"
        let timeZone = NSTimeZone(name: NSTimeZone.systemTimeZone().name)
        dateFormatter.timeZone = timeZone
        
        
        var dStr = dateFormatter.stringFromDate(date)
        return dateFormatter.dateFromString(dStr)!
        
    }

NSDateをStringに変換する

  func toStr(date:NSDate) -> String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy/MM/dd HH:mm"
        let timeZone = NSTimeZone(name: NSTimeZone.systemTimeZone().name)
        dateFormatter.timeZone = timeZone
        
        
        var dStr:String = dateFormatter.stringFromDate(date)
        return dStr
        
    }

Related Contents

Pickup Contents