gpt4 book ai didi

swift - 使用 NSDate 获取星期几

转载 作者:IT王子 更新时间:2023-10-29 04:57:37 26 4
gpt4 key购买 nike

我创建了一个方法,该方法应该接受“YYYY-MM-DD”形式的字符串并吐出一个代表日期位置相对于它所在的星期的 int(无论它是否在月份之间重叠) .所以例如星期日=1 星期一=2 等等。

这是我的代码:

    func getDayOfWeek(today:String)->Int{

var formatter:NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "YYYY-MM-DD"
var todayDate:NSDate = formatter.dateFromString(today)!
var myCalendar:NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
var myComponents = myCalendar.components(NSCalendarUnit.WeekdayOrdinalCalendarUnit, fromDate: todayDate)
var weekDay = myComponents.weekdayOrdinal
return weekDay
}

我知道 NSCalendarUnit.WeekdayOrdinalCalendar 是错误的,但我已经尝试过我认为最合乎逻辑的组合。并且还弄乱了 myComponents.weekdayOrdinal,例如使用 mycomponents.day.weekday

以下是我的选择:

static var EraCalendarUnit: NSCalendarUnit { get }
static var YearCalendarUnit: NSCalendarUnit { get }
static var MonthCalendarUnit: NSCalendarUnit { get }
static var DayCalendarUnit: NSCalendarUnit { get }
static var HourCalendarUnit: NSCalendarUnit { get }
static var MinuteCalendarUnit: NSCalendarUnit { get }
static var SecondCalendarUnit: NSCalendarUnit { get }
static var WeekCalendarUnit: NSCalendarUnit { get }
static var WeekdayCalendarUnit: NSCalendarUnit { get }
static var WeekdayOrdinalCalendarUnit: NSCalendarUnit { get }
static var QuarterCalendarUnit: NSCalendarUnit { get }
static var WeekOfMonthCalendarUnit: NSCalendarUnit { get }
static var WeekOfYearCalendarUnit: NSCalendarUnit { get }
static var YearForWeekOfYearCalendarUnit: NSCalendarUnit { get }
static var CalendarCalendarUnit: NSCalendarUnit { get }
static var TimeZoneCalendarUnit: NSCalendarUnit { get }

我不清楚,因为没有 DayOfWeekUnit 选项(或类似的东西)。

最佳答案

swift 3 和 4

检索星期几在 Swift 3 中得到了极大的简化,因为 DateComponents 不再是可选的。这是作为扩展:

extension Date {
func dayNumberOfWeek() -> Int? {
return Calendar.current.dateComponents([.weekday], from: self).weekday
}
}

// returns an integer from 1 - 7, with 1 being Sunday and 7 being Saturday
print(Date().dayNumberOfWeek()!) // 4

如果您正在寻找星期几的书面本地化版本:

extension Date {
func dayOfWeek() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
return dateFormatter.string(from: self).capitalized
// or use capitalized(with: locale) if you want
}
}

print(Date().dayOfWeek()!) // Wednesday

关于swift - 使用 NSDate 获取星期几,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25533147/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com