ios - FSCalendar select day 选择前一天 23:00
问题描述
我在 Swift 应用程序中使用 FSCalendar,当用户选择一天时,我正在打印选定的日期,它会在前一天的 23:00 打印。我不确定为什么以及如何解决这个问题。我在西班牙。也许这与你在哪里和你当地的时间有关?
这就是我打印所选日期的方式:
extension CalendarDataViewViewController: FSCalendarDataSource {
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd hh:mm:ss"
let now = df.string(from: date)
logger.debug("Date: \(date)")
}
}
这就是我选择 18 March 时打印的内容:
21:01:24.646 DEBUG CalendarDataViewViewController.calendar():258 - Date: 2021-03-17 23:00:00 +0000
解决方案
您的代码创建一个日期格式化程序,使用该格式化程序将返回的日期转换为日期字符串,然后忽略它并简单地打印以 UTC 显示的日期。(注意输出Date: 2021-03-17 23:00:00 +0000
)
将您的日志命令更改为:
logger.debug("Date: \(now)")
now
顺便说一句,对于保存用户选择的不是当前日期的日期,变量名称是一个糟糕的选择。
我建议将返回的日期参数selectedDate
和String
格式化程序的输出重命名为selectedDateString
编辑:
考虑这段代码:
import Foundation
func dateStringFromDate(_ inputDate: Date) -> String {
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd hh:mm:ss a"
let dateString = df.string(from: inputDate)
return dateString
}
func isoDateStringFromDate(_ inputDate: Date) -> String {
let df = ISO8601DateFormatter()
df.formatOptions = .withInternetDateTime
df.timeZone = TimeZone.current //Force the formatter to express the time in the current time zone, including offset
let dateString = df.string(from: inputDate)
return dateString
}
let now = Date()
print("Current timezone = \(TimeZone.current)")
print("now in 'raw' format = \(now)")
let localizedDateString = DateFormatter.localizedString(from: now,
dateStyle: .medium,
timeStyle: .medium)
print("localizedString for the current date = \(localizedDateString)")
print("dateStringFromDate = \(dateStringFromDate(now))")
print("isoDateStringFromDate = \(isoDateStringFromDate(now))")
现在,在美国东部时间 3 月 18 日星期四晚上 9:16 左右,记录了以下内容:
当前时区 = America/New_York(当前)
现在采用“原始”格式 = 2021-03-19 01:16:52 +0000
当前日期的本地化字符串 = 2021 年 3 月 18 日晚上 9:16:52
dateStringFromDate = 2021-03 -18 09:16:52 PM
isoDateStringFromDate = 2021-03-18T21:16:52-04:00
“原始”日期格式为 GMT,偏移值为 0。在该格式中,在 GMT 中,日历日期已经是 3 月 19 日。(因为 GMT 比 EDT 早 4 小时)
类函数NSDateFormatter.localizedString(from:dateStyle:timeStyle)
显示当前时区的日期并使用设备的区域设置。和参数使您可以选择是否以及以何种格式(短、中或长)显示日期或时间dateStyle
。timeStyle
显示遵循ISO8601标准ISO8601DateFormatter
中的约定的日期。上面的函数使用选项以 ISO8601“互联网日期和时间”格式表示日期。我强制该日期在当地时区,因此它显示的日期与 GMT 有 -4 小时的偏移(因为它是 EDT,我居住的东部夏令时。)isoDateStringFromDate(:)
.withInternetDateTime
该功能dateStringFromDate(_:)
与您的功能略有不同。它返回当前时区的日期字符串,使用 12 小时时间和 AM/PM 字符串。
推荐阅读
- java - 如何使笔记可删除或可以更改
- c# - android设备上的套接字连接被拒绝错误
- spring-boot - 无法在 Spring Boot 中创建数据并将其插入到新表中
- python - 如何在这段代码中实现多处理?
- reactjs - 这进入无限循环如何防止这种情况并更新我的状态待办事项
- php - JS - 如何将 JSON 对象的项目移动到另一个位置
- javascript - 如何在另一个页面 html 中包含 html 和 javascript?
- wpf - MVVM ListView SelectedItem 属性
- java - 使用 OpenSAML2 API 的 Azure AD 单一登录
- apache-spark - 识别与 PySpark 数据帧中的当前值不同的最新记录