从当前日期减去一定天数并以特定日期格式打印

Take a certain amount of days off the current date and print with certain date format

我如何将当前日期减去一定天数(减去一天)并以特定日期格式打印到控制台。

我目前正在使用:

print((Calendar.current as NSCalendar).date(byAdding: .day, value: -1, to: Date(), options: [])!)

将日期和时间打印为:

yyyy-MM-dd HH:MM:SS +0000

但我希望它打印成这样:

dd-MM-yyyy

这可能吗?

最好将其分成几行更容易 readable/maintainable 行。首先,计算你想要的日期,然后应用日期格式化程序。

let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"

print(dateFormatter.stringFromDate(yesterday))

swift3.0版本

let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
if let yesterday = yesterday {
    print(dateFormatter.string(from: yesterday))
}else{
    print("Date incorrectly manipulated")
}

您不应为 Date 格式字符串使用固定格式。因为您可能有来自世界各地的用户,他们看日期的方式不同。

您应该使用模板格式。您只需指定要显示的组件及其顺序,例如:

let dateFormatter = DateFormatter()
// dateFormatter.locale = Locale(identifier: "bn-BD") // Enable this line only at the time of your debugging/testing
dateFormatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "ddMMyyyy",
                                                options: 0,
                                                locale: dateFormatter.locale)

let date = Calendar.current.date(byAdding: .day, value: -1, to: Date())
if let date = date {
    let dateString = dateFormatter.string(from: date)
    print(dateString)
}

You shouldn't set your locale by yourself. It's done by the framework. You should only set your locale manually only at the time of testing your app.

在上面的示例中,我将 Locale 用作 "bn-BD",这意味着 孟加拉语中的孟加拉语 。您可以找到语言环境列表 here