[英]How to get the day of the week from a date in Swift
I can print the date in this format: Mon, Mar 19, 2018, but I am not sure how to get the Day of the week in this format. 我可以使用以下格式打印日期:2018年3月19日,星期一,但是我不确定如何以这种格式获取星期几。
Please help 请帮忙
let dateFormatter = DateFormatter()
// uncomment to enforce the US locale
// dateFormatter.locale = Locale(identifier: "en-US")
dateFormatter.setLocalizedDateFormatFromTemplate("EEE MMM d yyyy")
print(dateFormatter.string(from: Date())) // "Tue, Mar 20, 2018" for en-US locale
Note that I am using a template to provide the exact format, therefore the format will be properly localized in every language. 请注意,我正在使用模板来提供确切的格式,因此该格式将正确地本地化为每种语言。
With swift 4 迅捷4
func timeStamp()->String {
let dateFormater = DateFormatter()
dateFormater.locale = Locale(identifier: "en-US")
dateFormater.setLocalizedDateFormatFromTemplate("EEE MMM d yyyy")
return dateFormatter.string(from: Date())
}
Use it. 用它。
let getTimeStamp = timeStamp()
print(getTimeStamp)
dateFormatter.dateFormat = "EEE, MMM dd, yyyy" dateFormatter.dateFormat =“ EEE,MMM dd,yyyy”
For dat of week in alphabets, you use EEEE or EEE similar to MMM & yyyy for month year. 对于一周的字母,您将EEEE或类似于MMM和yyyy的EEE用于月份年份。
The best way to change your date is follow this method. 更改日期的最佳方法是遵循此方法。
func ChangeDateFormat(date:String,FromFormat: String, ToFormat: String) -> String {
let dateFormatter1 = DateFormatter()
dateFormatter1.dateFormat = FromFormat
let myDate = dateFormatter1.date(from: date)
dateFormatter1.dateFormat = ToFormat
if(myDate != nil){
let Date = dateFormatter1.string(from: myDate!)
return Date
}
else{
return ""
}
}
and then you can use this method like 然后您可以使用这种方法
String(ChangeDateFormat(date: StartDate, FromFormat: "yyyy-MM-dd hh:mm:ss a", ToFormat: "MMM d, yyyy"))
You can pass your date format in which format do you want in your case it should be 您可以传递日期格式,在这种情况下,您需要使用哪种格式
String(ChangeDateFormat(date: StartDate, FromFormat: "Pass your date format", ToFormat: "EEE MMM d, yyyy"))
Rather than needing to spell out a date format. 无需拼出日期格式。 I would simplify it further to:
我将进一步简化为:
dateFormatter.dateStyle = .full
Or if you just want the day: 或者,如果您只想要这一天:
dateFormatter.dateFormat = "EEEE"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.