从DateFormatter输出错误

时间:2019-05-10 05:55:06

标签: ios swift cocoa-touch nsdate nsdateformatter

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

1 个答案:

答案 0 :(得分:0)

Date始终采用任何编程语言的UTC,没有时区。 DateFormatter用于通过提供时区来以本地/本地化格式显示Date

Date Formatter允许您将其转换为人类可读的字符串。 在手机中:

  1. 如果您具有中央服务器/数据库,则应将日期保存为UTC。
  2. 何时需要在手机上显示,请使用时区将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
}