如何在 swift 中从两天中获取日期名称
Posted
技术标签:
【中文标题】如何在 swift 中从两天中获取日期名称【英文标题】:How get days name from two days in swift 【发布时间】:2019-05-28 12:59:37 【问题描述】:我有两个日期,date1 和 date2,我想要 date1 和 date 2 之间的天数
例子:
let date1 = 28-May-2019,
let date2 = 31-May-2019
预期输出
[周二、周三、周五]
【问题讨论】:
***.com/questions/32536612/… 然后将这些“Date”的对象转换成你想要的字符串表示形式。 【参考方案1】: let date1Str = "28-May-2019"
let date2Str = "31-May-2019"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateFormatter.locale = Locale(identifier: "en_US")
var date1 = dateFormatter.date(from:date1Str)!
var date2 = dateFormatter.date(from:date2Str)!
let dayFormatter = DateFormatter()
dayFormatter.dateFormat = "EEE"
while date1 <= date2
let dayInWeek = dayFormatter.string(from: date1)
print(dayInWeek)
date1 = Calendar.current.date(byAdding: .day, value: 1, to: date1)!
【讨论】:
【参考方案2】:以下代码为您提供两个日期之间的天数,并应说明日历的诡计。
let calendar = Calendar.current
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MMM-yyyy"
let dayFormatter = DateFormatter()
dayFormatter.dateFormat = "EEE"
let dateFrom = dateFormatter.date(from: "28-May-2019")!
let dateTo = dateFormatter.date(from: "31-May-2019")!
var days: [String] = []
var date = dateFrom
while date <= dateTo
let day = dayFormatter.string(from: date)
days.append(day)
date = calendar.date(byAdding: .day, value: 1, to: date)!
print(days)
【讨论】:
【参考方案3】:试试这个 -
func getWeekdays(dateOne firstDateStr: String, dateTwo secondDateStr: String) -> [String]
let dateformatter = DateFormatter()
dateformatter.dateFormat = "dd-MMM-yyyy"
guard let firstDate = dateformatter.date(from: firstDateStr),
let secondDate = dateformatter.date(from: secondDateStr) else
return []
let calendar = Calendar.current
let numberOfDays: Int
if firstDate > secondDate
numberOfDays = (calendar.dateComponents([.day], from: secondDate, to: firstDate).day ?? 0)
else
numberOfDays = (calendar.dateComponents([.day], from: firstDate, to: secondDate).day ?? 0)
dateformatter.dateFormat = "EEE"
let days = (0...numberOfDays).compactMap day -> String? in
if let date = calendar.date(byAdding: .day, value: day, to: firstDate)
return dateformatter.string(from: date)
return nil
print(days)
return days
【讨论】:
不要硬编码自己的工作日名称。使用DateFormatter
或使用Calendar
中的各种工作日名称属性获取名称。以上是关于如何在 swift 中从两天中获取日期名称的主要内容,如果未能解决你的问题,请参考以下文章