【问题标题】:How to determine the next days of the week if I know the current day?如果我知道当前日期,如何确定一周的下几天?
【发布时间】:2019-09-11 07:39:44
【问题描述】:

我创建了一个天气应用程序,并为此使用了 API。 (我使用 OpenWeatherMap 和 API 作为“调用 5 天 / 3 小时预报数据”) 我得到了我需要的所有信息。

然后我得到了一周中所有日子的数据。例如,周一气温 22 度,周二气温 12 度等。

我可以获取当前星期几并添加到字典中。

但我无法获得新的 dayName(星期几)。我需要做什么? 我需要帮助获取一周中接下来几天的名称及其索引。然后将键值添加到字典中。

// Indexed all days of the week Sun, Mon, Wed and a t.c             
let setWeekDay = IndexSet([1, 2, 3, 4, 5, 6, 7]) 

//I detected current day of the weak and added to dictionary
var weakDay = [String:Int]()
let calendar = Calendar.current
var weekday =  calendar.component(.weekday, from: Date())
let components = DateComponents(weekday: weekday)

var dayName = calendar.nextDate(after: Date(), matching: components, matchingPolicy: .nextTime)?.Days()

weakDay = [dayName!:weekday]

if let nextWeekday = setWeekDay.integerGreaterThan(weekday) {
    weekday = nextWeekday
    } else {
        weekday = setWeekDay.first!
    }


...
// I extended date formatter
extension Date{
    func Days() -> String{
        let dataFormatter = DateFormatter()
        dataFormatter.dateStyle = .short
        dataFormatter.dateFormat = "EEEE"
        return dataFormatter.string(from: self)
    }
}

//This is dictionary will be change key and value dynamically.

//I need got dictionary as:
let weakDay = [
                "Sunday": 1,
                "Monday": 2,
                "Tuesday": 3,
                "Wednesday": 4,
                "Thursday": 5,
                "Friday": 6,
                "Saturday": 7,
                ]

【问题讨论】:

  • 你的问题不清楚。请更好地解释您需要什么帮助。
  • 顺便说一句 - 不要硬编码工作日名称和数字。 Calendar 类为您提供工作日名称。
  • 您好,抱歉英语不好!我需要帮助获取一周中接下来几天的名称及其索引。然后将键值添加到字典中。
  • 希望能把问题解释的更清楚)

标签: swift calendar nsdatecomponents


【解决方案1】:

感谢所有人的帮助,但我自己找到了问题的答案! 我需要做什么:

if let cell = tableView.dequeueReusableCell(withIdentifier: "daysId", for: indexPath) as? DaysTVCell {

            var nameWeakAndIndex = [String:Int]()

            var dateComponents = DateComponents()
            dateComponents.setValue(1, for: .day);
            var now = Date()

            for index in 0...5 {

                let tomorrow = Calendar.current.date(byAdding: dateComponents, to: now)

                let detectDayIndex = index

                nameWeakAndIndex = [now.Days():detectDayIndex]

                now = tomorrow!

                daysWeak.sort(by: { (nameWeakAndIndex[$0.dayOfTheWeak] ?? 6) > (nameWeakAndIndex[$1.dayOfTheWeak] ?? 6) })
            }


            let day = daysWeak[indexPath.row]
            cell.configureCell(daysForecast: day)
            return cell

【讨论】:

    猜你喜欢
    • 2011-09-26
    • 2022-12-11
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多