ios 获取年月日是周几 星期一返回周一 星期二返回周二 星期三返回周三 星期四返回周四 星期五返回周五 星期六返回周六 星期天返回周天
可以使用 NSDateFormatter 类和 NSCalendar 类来获取年月日对应的周几。
首先,需要获取当前时间的年月日,可以使用 NSDate 类和 NSDateFormatter 类来进行格式化:
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let formattedDate = dateFormatter.string(from: date)
接下来,使用 NSCalendar 类的 component(_:from:) 方法来获取当前日期对应的星期几:
let calendar = Calendar.current
let weekDay = calendar.component(.weekday, from: date)
最后,根据星期几的值来判断返回的周几字符串:
var weekDayString = ""
switch weekDay {
case 1:
weekDayString = "周日"
case 2:
weekDayString = "周一"
case 3:
weekDayString = "周二"
case 4:
weekDayString = "周三"
case 5:
weekDayString = "周四"
case 6:
weekDayString = "周五"
case 7:
weekDayString = "周六"
default:
break
}
完整的代码示例如下:
import UIKit
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let formattedDate = dateFormatter.string(from: date)
let calendar = Calendar.current
let weekDay = calendar.component(.weekday, from: date)
var weekDayString = ""
switch weekDay {
case 1:
weekDayString = "周日"
case 2:
weekDayString = "周一"
case 3:
weekDayString = "周二"
case 4:
weekDayString = "周三"
case 5:
weekDayString = "周四"
case 6:
weekDayString = "周五"
case 7:
weekDayString = "周六"
default:
break
}
print("\(formattedDate) 是\(weekDayString)")
输出的结果会是当前日期对应的年月日和周几,例如:"2022-07-25 是周一"
原文地址: https://www.cveoy.top/t/topic/iDG4 著作权归作者所有。请勿转载和采集!