52
45

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

日付の計算【Swift 3.0】

Last updated at Posted at 2016-11-28

本日を書式指定して文字列で取得


/**
  本日を書式指定して文字列で取得     

 - parameter format: 書式(オプション)。未指定時は"yyyy/MM/dd HH:mm:ss" 
 - returns: 本日の日付
*/
func getToday(format:String = "yyyy/MM/dd HH:mm:ss") -> String {
        
    let now = Date()
    let formatter = DateFormatter()
    formatter.dateFormat = format
    return formatter.string(from: now as Date)
}

// ex.
print(getToday()) // 2016/11/28 14:41:07
print(getToday(format:"yyyy-MM-dd")) // 2016-11-28

n週間後(前)の日付を求める

/**
  n週間後(前)の日付を取得     

 - parameter week: n(週) 
 - returns: 算出後の日付
*/
func getDateBeforeOrAfterSomeWeek(week:Double) -> Date {
        
    let now = Date()
    var resultDate:Date
        
    if week > 0 {
        resultDate = Date(timeInterval: 604800*week, since: now as Date)
    } else {
        resultDate = Date(timeInterval: -604800*fabs(week), since: now as Date)
    }
        
    return resultDate
        
}

// ex. 
print(getDateBeforeOrAfterSomeWeek(week: 2))  // 2週間後
print(getDateBeforeOrAfterSomeWeek(week: -2)) // 2週間前

2つの日付の差(n日)を求める

/**
  2つの日付の差(n日)を取得   
  
 - parameter date: 日付
 - parameter anotherDay: 日付(オプション)。未指定時は当日が適用される
 - returns: 算出後の日付
*/
func getIntervalDays(date:Date?,anotherDay:Date? = nil) -> Double {
        
    var retInterval:Double!
        
    if anotherDay == nil {
        retInterval = date?.timeIntervalSinceNow
    } else {
        retInterval = date?.timeIntervalSince(anotherDay!)
    }
        
    let ret = retInterval/86400
        
    return floor(ret)  // n日
}

// ex. 2つの日付の差
print(getIntervalDays(date: date1,anotherDay: date2))
// ex. 本日との差
print(getIntervalDays(date: date1))

年、月、日、時、分、秒単位の日付計算


// swift 3.0

/**
 日付の計算
     
 - parameter year: 年の増減値。マイナス指定可能
 - parameter month: 月の増減値。マイナス指定可能
 - parameter day: 日の増減値。マイナス指定可能
 - parameter hour: 時の増減値。マイナス指定可能
 - parameter minute: 分の増減値。マイナス指定可能
 - parameter second: 秒の増減値。マイナス指定可能
 - parameter baseDate: 基準日(オプション)。指定した場合はこの日付を基準にする
     
 - returns: 計算結果の日付
 */
    
func calcDate(year:Int ,month:Int ,day:Int ,hour:Int ,minute:Int ,second:Int ,baseDate:String? = nil) -> Date {
        
    let formatter = DateFormatter()
    formatter.locale = NSLocale(localeIdentifier: "ja_JP") as Locale
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
    var components = DateComponents()
        
    components.setValue(year,for: Calendar.Component.year)
    components.setValue(month,for: Calendar.Component.month)
    components.setValue(day,for: Calendar.Component.day)
    components.setValue(hour,for: Calendar.Component.hour)
    components.setValue(minute,for: Calendar.Component.minute)
    components.setValue(second,for: Calendar.Component.second)
        
    let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
        
    let base:Date?
        
    if let _ = baseDate {
        if let _ = formatter.date(from: baseDate!) {
            base = formatter.date(from: baseDate!)!
        } else {
            print("baseDateの日付変換に失敗したので本日を使用します")
            base = Date()
        }
    } else {
        base = Date()
    }
    
    return calendar.date(byAdding: components, to: base!)!
}

// ex. 本日から1年と2ヶ月後の日付を取得
print("calc date => \(calcDate(year:1,month:2,day:0,hour:0,minute:0,second:0))")

// ex. 2015-10-01 00:00:00 から3ヶ月前の日付を取得
print("calc date => \(calcDate(year:0,month:-3,day:0,hour:0,minute:0,second:0,baseDate: "2015-10-01 00:00:00"))"))


/**** calcDateのラッパー **************************/

// 年の増減
func calcDateYear(year:Int,baseDate:String? = nil) -> Date {
    return calcDate(year:year,month:0,day:0,hour:0,minute:0,second:0,baseDate: baseDate)
}

// 月の増減
func calcDateMonth(month:Int,baseDate:String? = nil) -> Date {
    return calcDate(year:0,month:month,day:0,hour:0,minute:0,second:0,baseDate: baseDate)
}

// 日の増減
func calcDateDay(day:Int,baseDate:String? = nil) -> Date {
    return calcDate(year:0,month:0,day:day,hour:0,minute:0,second:0,baseDate: baseDate)
}


基準日から本日までの日付を配列で取得


// swift 3.0

/**
 基準日から本日までの日付を配列で返す
     
 - parameter start: 基準日     
 - parameter max: 格納上限     
 - returns : 日付文字列の配列
 */
    
func getDaysArrayToToday(start:String,max:Int) -> [String] {
    
    var result:[String] = []
    let formatter = DateFormatter()
    formatter.locale = NSLocale(localeIdentifier: "ja_JP") as Locale
    formatter.dateFormat = "yyyy-MM-dd"
    
    // 今日
    let todayStr = formatter.string(from: Date())
    let startDate = formatter.date(from: start)!

    
    var components = DateComponents()
    let calendar = Calendar(identifier: Calendar.Identifier.gregorian)

    for i in 0 ..< max {

        components.setValue(i,for: Calendar.Component.day)
        let wk = calendar.date(byAdding: components, to: startDate)!
        let wkStr = formatter.string(from: wk)
        if wkStr > todayStr {
            break
        } else {
            result.append(wkStr)
        }
    }
    
    return result
}

// ex 本日=2016-12-24
let startDate = "2016-12-20"
print(getDaysArrayToToday(start: startDate, max: 10))
// ["2016-12-20", "2016-12-21", "2016-12-22", "2016-12-23", "2016-12-24"]

 

Swift用日付管理ライブラリ ⇒ 【Swift4】DateManager【iOS】

52
45
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
52
45

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?