如何迅速开始和结束一周? [英] How to get start and end of the week in swift?

查看:57
本文介绍了如何迅速开始和结束一周?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何快速开始和结束一周?
这是我的代码

How to get start and end of the week in swift ? this is my code

extension Date {
    var startOfWeek: Date? {
        let gregorian = Calendar(identifier: .gregorian)
        guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
        return gregorian.date(byAdding: .day, value: 1, to: sunday)
    }

    var endOfWeek: Date? {
        let gregorian = Calendar(identifier: .gregorian)
        guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
        return gregorian.date(byAdding: .day, value: 7, to: sunday)
    }
}

我这样呼叫

let startWeek = Date().startOfWeek
let endWeek = Date().endOfWeek
print(startWeek!)
print(endWeek!)
var dateFormat1 = DateFormatter()
dateFormat1.dateFormat = "dd-MM-yy"
let startWeek2 = dateFormat1.string(from: startWeek!)
var dateFormat12 = DateFormatter()
dateFormat12.dateFormat = "dd-MM-yy"
let endWeek2 = dateFormat12.string(from: endWeek!)
print(startWeek2)
print(endWeek2)

和输出

2017-09-24 18:30:00 +0000
2017-09-30 18:30:00 +0000
25-09-17
01-10-17


推荐答案

您的代码运行正常。如果您要在Playground中运行代码,则可以看到实际的 Date 对象,而不是String表示形式。即使您没有指定 DateFormatter ,在执行 print(Date())时,在后台也可以使用Swift使用 DateFormatter 打印 Date 对象,因此该值将是相对时间而不是所提供的绝对时间点通过 Date 对象。

Your code is working perfectly fine. If you would run your code in a Playground, you could see the actual Date objects rather than there String representations. Even if you don't specify a DateFormatter, under the hood, when doing print(Date()), Swift uses a DateFormatter to print Date objects and hence that value will be a relative time instead of the absolute point in time provided by the Date object.

在操场上,您可以看到实际的 startOfWeek 2017年9月25日上午12:00 ,而 endOfWeek 2017年10月1日上午12:00 ,这是当前一周的正确值。

In a Playground you can see that the actual startOfWeek is "Sep 25, 2017 at 12:00 AM", while the endOfWeek is "Oct 1, 2017 at 12:00 AM", which are the correct values for the current week.

Don不要使用 print(Date())来检查 Date 对象的正确性,因为如您所见,它由于使用了底层 DateFormatter ,将产生意外结果。

Don't use print(Date()) for checking the correctness of Date objects, since as you can see, it will yield unexpected results due to the underlying DateFormatters used.

这篇关于如何迅速开始和结束一周?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆