Get Weekday from Date - Swift 3

后端 未结 6 940
时光说笑
时光说笑 2021-01-01 08:21

I have looked around a bit, but didnt find a quick answer for this in swift 3. I get todays weekday like this:

let weekday = Calendar.current.component(.week         


        
相关标签:
6条回答
  • 2021-01-01 08:59

    Swift5 get week day from DateFormatter

     func getTodayWeekDay()-> String{
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "EEEE"
            let weekDay = dateFormatter.string(from: Date())
            return weekDay
      }
    
    0 讨论(0)
  • 2021-01-01 09:01
    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy"
    //OR dateFormatter.dateFormat = "EEEE, MMMM dd, yyyy"
    let currentDateString: String = dateFormatter.string(from: date)
    print("Current date is \(currentDateString)")
    

    Current date is Monday, June 29, 2017

    0 讨论(0)
  • 2021-01-01 09:02

    If you want dayNumber component in TimeZone

    func dayNumberOfWeek() -> Int? {
        let timeZone = TimeZone(abbreviation: "EDT")
        let component =  Calendar.current.dateComponents(in: timeZone!, from: self)
        return  component.day
    }
    
    0 讨论(0)
  • 2021-01-01 09:04

    Weekday by default consider first weekday as Sunday, if you wanna support generic context use this extension.

    extension Date {
    
        var calendar: Calendar { Calendar.current }
    
        var weekday: Int {
            (calendar.component(.weekday, from: self) - calendar.firstWeekday + 7) % 7 + 1
        }
    }
    
    0 讨论(0)
  • 2021-01-01 09:21

    To get local format you can use:

    extension Date{
    
    func stringValueFullWithTime()-> String?{
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .full
        dateFormatter.timeStyle = . short
        dateFormatter.locale = Locale.current
        return dateFormatter.string(from: self)
    }
    

    This will print as german local:
    Sonntag, 11. November 2018 um 11:17

    0 讨论(0)
  • 2021-01-01 09:25

    Presumably you have a Date already?

    let weekday = Calendar.current.component(.weekday, from: myDate)
    

    Maybe you want the name of the weekday?

    let f = DateFormatter()
    
    f.weekdaySymbols[Calendar.current.component(.weekday, from: Date()) - 1]
    

    The -1 is added at the end because Calendar.current.component(.weekday, from: Date()) returns values from 1-7 but weekdaySymbols expects array indices.

    Investigate the NSCalendar/DateComponents api or edit your question to be more specific if you need help with the DateComponents api.

    0 讨论(0)
提交回复
热议问题