NSCalendarを用いて
前日の日付を取得したいのですがどのようにすればよいのでしょうか?
日付が、例えば、1月1日だったら、前日の12月31日を取得
できるようにしたいです。(前日が31日か30日なのかも判断)
調べても、あまり参考になるようなサイトが見つからなかったので、質問させていただきました。
//追記
swift
1 2let cal = NSCalendar(identifier: NSCalendarIdentifierGregorian)! 3 4// 入力年月用書式設定 5let dateFormatter = NSDateFormatter() 6 7//現在 8var now = NSDate() 9//年を取得 10let year : String = String(cal.component(.Year, fromDate: now)) 11//月を取得 12let month : String = String(cal.component(.Month, fromDate: now)) 13//日を取得 14let day : String = String(cal.component(.Day, fromDate: now)) 15 16dateFormatter.dateFormat = "yyyy/MM/dd" 17let inputDate = dateFormatter.dateFromString(year + "/" + month + "/" + day) 18 19// 入力年月日の前日 "Nov 30, 2015, 12:00 AM" 20let inputDateBeforeDay = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -1, toDate: inputDate!, options: NSCalendarOptions.init(rawValue: 0)) 21 22// 今日 23var currentDate = NSDate() 24// 昨日 25var yesterday : String = String(NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -1, toDate: currentDate, options: NSCalendarOptions.init(rawValue: 0))) 26//曜日の取得 27let date1: NSDate = NSDate() 28let cal1: NSCalendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)! 29let comp: NSDateComponents = cal1.components( 30 [NSCalendarUnit.Weekday], 31 fromDate: date1 32) 33let weekday: Int = comp.weekday 34let weekdaySymbolIndex: Int = weekday - 2 35let formatter: NSDateFormatter = NSDateFormatter() 36 37formatter.locale = NSLocale(localeIdentifier: "ja") 38print(formatter.shortWeekdaySymbols[weekdaySymbolIndex]) 39 40yesterday += String("(" + formatter.shortWeekdaySymbols[weekdaySymbolIndex] + ")")
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/12/09 00:59 編集
2015/12/09 04:37
2015/12/09 05:14