如何获取Swift日期的工作日字符串表示

时间:2017-02-10 18:27:24

标签: ios swift

我正试图获得约会的工作日(星期三,星期二),但我似乎无法找到真正获得字符串的好方法。这就是我正在做的事情:

internal func fromToday(daysAgo: Date) -> String {

    let calendar = NSCalendar.autoupdatingCurrent
    let startOfNow = calendar.startOfDay(for: Date())
    let startOfTimeStamp = calendar.startOfDay(for: daysAgo)
    let numDaysDifference = abs(calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp).day!)
    let daysAgoComponents = calendar.dateComponents([.weekday, .hour, .minute], from: daysAgo)

    var hour = daysAgoComponents.hour!
    var timeOfDay = "AM"

    if hour >= 13 {
        hour -= 12
        timeOfDay = "PM"
    }

    var res = "\(hour):\(daysAgoComponents.minute!)\(timeOfDay)"

    if calendar.isDateInYesterday(daysAgo) {
        res = "Yesterday"
    } else if numDaysDifference < 8 && numDaysDifference > 1 {
        res = stringFromWeekday(day: daysAgoComponents.weekday!) // HERE THIS IS WHAT IM ASKING ABOUT IGNORE OTHER IFS
    } else if numDaysDifference >= 8 {
        res = stringFromDate(day: daysAgo)
    }

    return res
}

fileprivate func stringFromWeekday(day: Int) -> String {
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US")

    if formatter.weekdaySymbols.count < day {
        print("ConversationTVC - \(day) is not a valid day of the week")
    }

    return formatter.weekdaySymbols[day]
}

具体来说,行:

else if numDaysDifference < 8 && numDaysDifference > 1 
    res = stringFromWeekday(day: daysAgoComponents.weekday!)` 

我认为这个问题与weekdaySymbols

有关

如何在给定日期的情况下获取X天前一周的字符串表示形式?

1 个答案:

答案 0 :(得分:0)

问题是我从一天开始减去1,工作日返回1-7,工作日符号为0-6