OStack程序员社区-中国程序员成长平台

标题: ios - 如何在swift 3中将日期范围转换为字符串? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:01
标题: ios - 如何在swift 3中将日期范围转换为字符串?

如何将日期转换为字符串格式?

我得到两个日期之间的日期(从开始到结束日期)。我正在使用以下方法

class Dates {
static func printDatesBetweenInterval(_ startDate: Date, _ endDate: Date) {
    var startDate = startDate
    let calendar = Calendar.current

    let fmt = DateFormatter()
    fmt.dateFormat = "yyyy-MM-dd"

    while startDate <= endDate {
        print(fmt.string(from: startDate))
        startDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
    }
}

static func dateFromString(_ dateString: String) -> Date {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"

    return dateFormatter.date(from: dateString)!
}}

在这里打印日期

Dates.printDatesBetweenInterval(Dates.dateFromString("2017-10-02"), Dates.dateFromString("2017-10-9"))

结果:

2017-10-02 2017-10-03 2017-10-04 2017-10-05 2017-10-06 2017-10-07 2017-10-08 2017-10-09

现在,我想将此日期以字符串格式传递给日历(我在应用程序中使用 FSCalendar 库)。我想要这种格式 示例:

["2017-10-02", "2017-10-03", "2017-10-04", "2017-10-05", "2017-10-06", "2017-10-07", "2017-10-08", "2017-10-09"]

谁能指导我。谢谢



Best Answer-推荐答案


static func getDatesStringBetweenInterval(_ startDate: Date, _ endDate: Date)-> String {
        var retval = "["

        var startDate = startDate
        let calendar = Calendar.current

        let fmt = DateFormatter()
        fmt.dateFormat = "yyyy-MM-dd"

        while startDate <= endDate {
            if startDate < endDate {
                retval.append("\"\(fmt.string(from: startDate))\", ")
            } else {
               retval.append("\"\(fmt.string(from: startDate))\"")
            }
            startDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
        }
        retval.append("]")

        return retval
    }

用法:

let aDate = Dates.dateFromString("2017-01-01")
let bDate = Dates.dateFromString("2017-01-05")
let datesString = Dates.getDatesStringBetweenInterval(aDate, bDate)
print(datesString)

关于ios - 如何在swift 3中将日期范围转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46811163/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4