xcode 从日期获取工作日 - Swift 3

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41068860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 18:24:08  来源:igfitidea点击:

Get Weekday from Date - Swift 3

xcodedateswift3

提问by Martin Vidic

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

我环顾四周,但没有在 swift 3 中找到一个快速答案。我今天的工作日是这样的:

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

But instead, i would like to get the weekday of a given date. How is this done? Thanx

但相反,我想获得给定日期的工作日。这是怎么做的?谢谢

回答by Joe Daniels

Presumably you have a Datealready?

想必你已经Date有了?

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 -1is added at the end because Calendar.current.component(.weekday, from: Date()) returns values from 1-7 but weekdaySymbols expects array indices.

-1是在结束时加入,因为Calendar.current.component(.weekday,来自:日期())1-7返回值,但预计weekdaySymbols阵列索引。

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

如果您需要有关 DateComponents api 的帮助,请调查NSCalendar/ DateComponentsapi 或编辑您的问题以使其更具体。

回答by Yakup Ad

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

当前日期是 2017 年 6 月 29 日,星期一

回答by Sukhwinder Singh

Swift4 get week day from DateFormatter

Swift4 从 DateFormatter 获取工作日

 func getTodayWeekDay()-> String{
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "EEEE"
        let weekDay = dateFormatter.string(from: Date())
        return weekDay
  }

回答by Yedy

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

这将打印为德国本地:
Sonntag,2018 年 11 月 11 日 11:17

回答by Devesh

If you want dayNumber component in TimeZone

如果你想要 TimeZone 中的 dayNumber 组件

func dayNumberOfWeek() -> Int? {
    let timeZone = TimeZone(abbreviation: "EDT")
    let component =  Calendar.current.dateComponents(in: timeZone!, from: self)
    return  component.day
}