从 DateFormatter 获取错误的输出

Getting wrong output from DateFormatter

我从下面的代码中获取上周的日期,一周从星期六开始。它正在获取日期(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

Date 在任何编程语言中始终使用 UTC,它没有时区。 DateFormatter 用于通过提供时区以 local/localised 格式显示 Date

Date Formatter 允许您将其转换为人类可读的字符串。 在 phone 秒内:

  1. 如果您使用中央 server/DB,那么您应该以 UTC 格式保存日期。
  2. 当时间显示在您的 phone 上时,使用时区将 UTC 转换为本地时间。

不要试图让它过于复杂。

使用以下代码查找上周的星期一和星期日:

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
}