我从以下代码获取上周日期,一周从星期六开始。正在获取日期(2019-04-27 18:30:00 +0000,019-05-04 18:30:00 +0000),但是当我尝试设置 DateFormatter 时,它正在获取日期(28 -04-2019 00:00:00,05-05-2019 00:00:00)。我希望每周从印度当地时间和日期的星期一开始。
var dateFormatter:DateFormatter!
var date:Date!
dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
date = Date()
var calendar = Calendar.current
calendar.firstWeekday = 2 // 1 is Sunday, 2 is Monday
let lastWeek = calendar.date(byAdding: .weekOfYear, value: -1, to: Date())
if let lastWeek = lastWeek {
var startOfLastWeek = Date()
var interval = TimeInterval(0)
_ = Calendar.current.dateInterval(of: .weekOfYear, start: &startOfLastWeek, interval: &interval, for: lastWeek)
let endOfLastWeek = startOfLastWeek.addingTimeInterval(interval)
print(startOfLastWeek)//2019-04-27 18:30:00 +0000
print(endOfLastWeek)//019-05-04 18:30:00 +0000
let startWeekString = dateFormatter.string(from: startOfLastWeek)
let endWeekString = dateFormatter.string(from: endOfLastWeek)
print(startWeekString)//28-04-2019 00:00:00
print(endWeekString)//05-05-2019 00:00:00
答案 0 :(得分:0)
Date
始终采用任何编程语言的UTC,没有时区。 DateFormatter
用于通过提供时区来以本地/本地化格式显示Date
。
Date Formatter
允许您将其转换为人类可读的字符串。
在手机中:
请勿过度使用它。
使用以下代码查找上周的星期一和星期日:
var date:Date!
dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
dateFormatter.timeZone=TimeZone.current
TimeZone.current
date = Date()
var calendar = Calendar.current
calendar.firstWeekday = 2 // 1 is Sunday, 2 is Monday
let lastWeek = calendar.date(byAdding: .weekOfYear, value: -1, to: Date())
if let lastWeek = lastWeek {
var startOfLastWeek = Date()
var interval = TimeInterval(0)
_ = Calendar.current.dateInterval(of: .weekOfYear, start: &startOfLastWeek, interval: &interval, for: lastWeek)
startOfLastWeek = calendar.date(byAdding: .weekday, value: 1, to: startOfLastWeek)!
print(interval)
interval = interval - 1
let endOfLastWeek = startOfLastWeek.addingTimeInterval(interval)
print(startOfLastWeek)//2019-04-27 18:30:00 +0000
print(endOfLastWeek)//019-05-04 18:30:00 +0000
let startWeekString = dateFormatter.string(from: startOfLastWeek)
let endWeekString = dateFormatter.string(from: endOfLastWeek)
print(startWeekString)//28-04-2019 00:00:00
print(endWeekString)//05-05-2019 00:00:00
}