3
1

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 1 year has passed since last update.

【Swift】前の○曜日の日付を出力する関数

Last updated at Posted at 2021-12-06

概要

直近の水曜日の日付(午前0時ちょうどの時刻)を出力したい場面があったので、関数を作ってみました。

コード

modulo演算を作っておきます。
参考:https://qiita.com/Ryuichirou/items/5ffed727c031290fed61

Utils.swift
import Foundation

infix operator %%
func %%(lhs: Int, rhs: Int) -> Int{
    return ((lhs % rhs) + rhs) % rhs
}

今日の曜日から、目的の曜日まで何日戻せば良いか計算して、Dateを出力します。
引数がStringだとヒューマンエラーが起こりそうなので、引数をenum(Weekday型)にしてコンパイル時にエラーがわかるようにしています。
(イニシャライザは要検討かも)

DateUtils.swift
import Foundation

class DateUtils {    
    class func dateOfLastWeekday (_ weekday:Weekday) -> Date {
        let dateFormatter = DateFormatter()
        let calendar = Calendar(identifier: .gregorian)
        let today = Date()
        dateFormatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "E", options: 0, locale: Locale(identifier: "en_US_POSIX"))
        let weekdayOfToday = dateFormatter.string(from: today)
        let interval = (Weekday(weekdayOfToday).order - weekday.order) %% 7
        let date = calendar.startOfDay(for: Calendar.current.date(byAdding: .day, value: interval * (-1), to: today)!)
        return date
    }

    enum Weekday {
        case Sunday
        case Monday
        case Tuesday
        case Wednesday
        case Thursday
        case Friday
        case Saturday

        init(_ E :String){
            switch E {
            case "Sun": self = .Sunday
            case "Mon": self = .Monday
            case "Tue": self = .Tuesday
            case "Wed": self = .Wednesday
            case "Thu": self = .Thursday
            case "Fri": self = .Friday
            case "Sat": self = .Saturday
            default: fatalError("Illegal weekday string \"\(E)\"")
            }
        }

        var order: Int {
            switch self {
            case .Sunday:    return 0
            case .Monday:    return 1
            case .Tuesday:   return 2
            case .Wednesday: return 3
            case .Thursday:  return 4
            case .Friday:    return 5
            case .Saturday:  return 6
            }
        }
    }
}

使い方

let lastWednesday = DateUtils.dateOfLastWeekday(.Wednesday)
print(lastWednesday)
// 2021-11-30 15:00:00 +0000 
// -> 日本標準時では2021-12-01 00:00:00 となり、水曜日の午前0時が出力されている
3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?