4
4

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:NSDateで翌日を得る

Last updated at Posted at 2016-08-28

OSX El Capitan(10.11.6)
Xcode 7.3.1
Swift version 2.2
を使用しております。

ちょっと前に
Swift:NSDateの年号を西暦表示
というのを書きました。

今回は単純に翌日を得る方法です(改良すれば好きな日に変更できます)。

方法その1
let date:NSDate = NSDate() //当日の日付を得る
let dateFormatter = NSDateFormatter()
//表示のためにフォーマット設定
dateFormatter.dateFormat = "MM/dd" // 日付フォーマットの設定

//当日をunixtime(1970/1/1 00:00:00 からの秒数表現)で得る
var time = date.timeIntervalSince1970
time += 60*60*24 //24時間後の時間を加算(60秒*60分*24時間)

//新しく日時取得        
let newDate:NSDate = NSDate.init(timeIntervalSince1970:time)

print("今日"+dateFormatter.stringFromDate(date))
print("明日"+dateFormatter.stringFromDate(newDate))

::結果
今日08/29
明日08/30

方法その2
let date:NSDate = NSDate() //当日の日付を得る
let dateFormatter = NSDateFormatter()
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
//年月日時間を取得するよう設定する
let flags: NSCalendarUnit = [.Year, .Month, .Day, .Hour, .Minute, .Second,]
//設定したフラグに沿ってデータ取得
let currentCalendar = calendar!.components(flags, fromDate: date)
//表示のためにフォーマット設定
dateFormatter.dateFormat = "MM/dd" // 日付フォーマットの設定

currentCalendar.day += 1//+1して翌日にする

//新しく日時取得        
let newDate:NSDate = calendar!.dateFromComponents(currentCalendar)!

print("今日"+dateFormatter.stringFromDate(date))
print("明日"+dateFormatter.stringFromDate(newDate))

::結果
今日08/29
明日08/30

日付を扱う関数に合わせて使いやすいやり方で使用するのがよいでしょう。

4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?