LoginSignup
0
0

More than 1 year has passed since last update.

日付関連

Last updated at Posted at 2021-07-28

全体

この記事は下の記事の一部です

日時の取得

まず今日が何日かを取得する方法です。
var now :Date = Date()
これでDateというstructのnow(この名前はなんでもいい)という変数を宣言して、そこに初期値としてDate()という今の日時を取得できる関数で今のDateの値を代入しています。

日時の表示

Date型をString型に変える処理をprintDayという関数を作って表示しています。
format(yyyyMMみたいな)を指定してString型に変更しているだけなので、printDayという名前はおかしいかなと思いましたが、他にいいものが思いつかなかったのでとりあえずこれでいきたいと思います。

この関数の引数はDate型とString型でそれぞれ
Date: Stringに直したいdate
String: format(yy.M.ddみたいな)
を指定しています。

DateFormatter型でformatterという定数をDateFormatter()で宣言して
このformatter
.calendarというプロパティをCalendar関数でgregorian(グレゴリオ暦のこと)にして
.dateFormatというプロパティに引数のf = "M/dd"を代入して設定しています。
DateFormatter型の.Stringメソッドを使ってDate型をString型に変更していると思われるんだけど詳しくわからなかったので要勉強。from:のところがいまいちよくわからないです。

printDay
func printDay(d: Date, f: String) -> String {
    let formatter :DateFormatter = DateFormatter()
    formatter.calendar = Calendar(identifier: .gregorian)
    formatter.dateFormat = f
    return formatter.string(from: d as Date)
}

表示する日付の変更

Date型のaddingTimeIntervalメソッドを使いたいんですけど、TimeIntervalではDoubleを使って欲しいみたいなので、Doubleをあげています。秒数で管理しているので、n日変更したいときはn*24*60*60のようにしてあげます。

changeDay
func changeDay(d :Date, i: Double) -> Date {
    let returnDate = d.addingTimeInterval(i*24*60*60)
    return returnDate
}

参考文献

https://developer.apple.com/documentation/foundation/timeinterval
https://www.ajinohiraki.info/entry/2018/09/17/012022
https://capibara1969.com/2100/
https://qiita.com/k-yamada-github/items/8b6411959579fd6cd995
printDay関数はこの人のやつが最終形態に近いです。

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