【问题标题】:Date array to String Array Swift日期数组到字符串数组 Swift
【发布时间】:2018-04-14 13:07:23
【问题描述】:

我有一个 .compactmap 函数,它获取过去一周的所有日期并在 Date 数组中返回它们:

func getCurrentWeek() -> [Date]{
    let calendar = Calendar.current
    let today = calendar.startOfDay(for: Date())
    let dayOfWeek = calendar.component(.weekday, from: today)
    let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: today)!       

    let days = (weekdays.lowerBound ..< weekdays.upperBound)
        .compactMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: today) }  // use `compactMap` in Xcode 9.3 and later
        .filter { !calendar.isDateInWeekend($0) }

    return days
}

我正在尝试将其用作标签,我需要它为字符串格式,但似乎无法更改函数以返回字符串数组。我试过这个:

func getCurrentWeek() -> [String]{
    let calendar = Calendar.current
    let today = calendar.startOfDay(for: Date())
    let dayOfWeek = calendar.component(.weekday, from: today)
    let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: today)!

    let formatter = DateFormatter()
    formatter.dateStyle = .short
    formatter.timeStyle = .none



    let days = (weekdays.lowerBound ..< weekdays.upperBound)
        .compactMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: today) }  // use `compactMap` in Xcode 9.3 and later
        .filter { !calendar.isDateInWeekend($0) }

    let myStringafd = formatter.string(from: days)


    return myStringafd
}

但不断收到此错误:

无法将“[日期]”类型的值转换为预期的参数类型“日期”

我知道这意味着什么,但我不确定如何解决这个问题并修复错误?

当前格式:

[2018-04-08 23:00:00 +0000, 2018-04-09 23:00:00 +0000, 2018-04-10 23:00:00 +0000, 2018-04-11 23: 00:00 +0000, 2018-04-12 23:00:00 +0000]

所需格式:

[“2018-04-08”、“2018-04-09”、“2018-04-10”、“2018-04-11”、“2018-04-12”]

【问题讨论】:

    标签: swift string date


    【解决方案1】:

    问题来了

      let myStringafd = formatter.string(from: days)
    

    这需要单个 Date 作为参数,但是你传递 days 这是 Dates 数组,你必须

    return days.map{ formatter.string(from: $0) }
    

    【讨论】:

    • let myStrings = days.map{ formatter.string(from: $0) }
    【解决方案2】:

    你也可以试试:

    for date in arrOfDates{
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "yyyy-MM-dd"
                let convdate =  dateFormatter.string(from: date)
                print(convdate)
            }
    

    【讨论】:

      猜你喜欢
      • 2017-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-22
      • 1970-01-01
      • 2016-07-04
      • 1970-01-01
      相关资源
      最近更新 更多