【问题标题】:Wrong date from components组件日期错误
【发布时间】:2021-10-12 18:13:27
【问题描述】:

所以这很有趣:

po Calendar.default.date(from: DateComponents(year: 2022, month: 1, hour: 16, minute: 1, second: 1, weekday: 1, weekOfMonth: 1))
▿ Optional<Date>
  ▿ some : 2021-12-26 23:01:01 +0000
    - timeIntervalSinceReferenceDate : 662252461.0

我预计是 2022 年 1 月 1 日,但我得到的是 2021 年 12 月 26 日?为什么要这样做?我做错了吗?

【问题讨论】:

    标签: ios swift date calendar nsdatecomponents


    【解决方案1】:

    这是因为您提供的日期组件是矛盾的。您有工作日 1(可能是星期日或星期一,具体取决于您所在的地区),但 2022 年 1 月 1 日是星期六。

    (当我认为您的意思是Calendar.current时,您还使用了Calendar.default?)

    如果你去掉weekDay这个词你会得到正确答案:

    Calendar.current.date(from: DateComponents(year: 2022, month: 1, hour: 16, minute: 1, second: 1, weekOfMonth: 1))
    
    // "Jan 1, 2022 at 4:01 PM"
    

    您还可以删除 weekOfMonth 术语,因为在指定实际日期时它是多余的。

    【讨论】:

    • 我删除了 weekOfMonth 并且它起作用了。谢谢! Calendar.default 存在于我创建的一个扩展中,通常是 autoUpdatingCurrent。
    • @xytor 没问题。如果您对它感到满意,如果您能接受答案,我们将不胜感激。
    • 我没有看到执行此操作的按钮。
    猜你喜欢
    • 2012-01-16
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    相关资源
    最近更新 更多