swift码3如何获得明天和昨天的日期(如有特殊情况)

时间:2022-08-25 11:05:07

This question already has an answer here:

这个问题已经有了答案:

i am work on data calendar for every current month and i should show 3 type of calculation for ( yesterday - today - tomorrow)

我每个月都在做数据日历,我应该给你看3种计算方式(昨天-今天-明天)

i have crash because of (index out of bound) for special case like if today date ( 31 May 2017 ) and i have array of May month if i try to continue my app and start calculation tomorrow i will have Error [because i should know its new month tomorrow ]

我已经崩溃,因为绑定(指数)等特殊情况如果今天日期(2017年5月31日)和我有一系列可以月如果我试着明天我将继续我的应用程序并开始计算错误(因为明天我应该知道它的新的月)

this is my code

这是我的代码

class ViewController: UIViewController {
    var dateComponents: DateComponents!
    var TimeToday :[String] = []
    var TimeTomorrow :[String] = []
    var TimeYesterday :[String] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        let dateDay = Date()
        let calendar = Calendar(identifier: .gregorian)
        dateComponents = calendar.dateComponents([.day, .month, .year], from: dateDay)
        done()
    }
    func done()  {
        //------ for tomorrow ------
        // month end day 31
        if (dateComponents.day! == 30){
            if(dateComponents.month! == 1 || dateComponents.month! == 4 || dateComponents.month! == 6 || dateComponents.month! == 7 || dateComponents.month! == 9 || dateComponents.month! == 11 ){
                TimeTomorrow.append("\(dateComponents.month!+1)")
            }
        // month end day 31
        }else if (dateComponents.day! == 31){
            if(dateComponents.month! == 3 || dateComponents.month! == 5 || dateComponents.month! == 8 ){
                TimeTomorrow.append("\(dateComponents.month!+1)")
            }else if(dateComponents.month! == 12){
                TimeTomorrow.append("\(dateComponents.year!+1)")
            }
         // month end day 29
        // special case for leap year i donot know how find it
        //****************************************************
            else if (dateComponents.day! == 29){
                if(dateComponents.month! == 2 || dateComponents.month! == 10  ){
                    TimeTomorrow.append("\(dateComponents.month!+1)")
                }
            }
        //------ for yesterday  ------
            if (dateComponents.month! == 12 || dateComponents.month! == 10 || dateComponents.month! == 8 || dateComponents.month! == 7 || dateComponents.month! == 5 || dateComponents.month! == 2){
                var day = dateComponents.date! - 1
                //fatal error: unexpectedly found nil while unwrapping an Optional value
                TimeYesterday.append("\(day)")
                TimeYesterday.append("30 - \(dateComponents.month! - 1)")
            }else {
                //////
            }
        }
    }
}

2 个解决方案

#1


49  

You should use Calendar method date(byAdding component:) to do your calendrical calculations and doing so you don't need to worry about those special cases:

您应该使用日历方法date(通过添加组件:)进行计算,这样您就不需要担心这些特殊情况:

extension Date {
    var yesterday: Date {
        return Calendar.current.date(byAdding: .day, value: -1, to: noon)!
    }
    var tomorrow: Date {
        return Calendar.current.date(byAdding: .day, value: 1, to: noon)!
    }
    var noon: Date {
        return Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
    }
    var month: Int {
        return Calendar.current.component(.month,  from: self)
    }
    var isLastDayOfMonth: Bool {
        return tomorrow.month != month
    }
}

Date().yesterday   // "Oct 28, 2017 at 12:00 PM"
Date()             // "Oct 29, 2017 at 12:54 PM"
Date().tomorrow    // "Oct 30, 2017 at 12:00 PM"

Date().yesterday.month   // 10
Date().isLastDayOfMonth  // false

#2


0  

I don't know if this helps you or not, but I would recommend not doing the math on NSDateComponents but rather on NSDate. Take a look at https://github.com/malcommac/SwiftDate a cocoapod for how to do things like call tomorrow on an NSDate. The cool thing about that pod is it uses Regions which helps for internationalization where the next day might start at sunset instead of mid nite.

我不知道这是否对你有帮助,但我建议不要在NSDateComponents上做数学运算,而是在NSDate上。看看https://github.com/malcommac/SwiftDate一个cocoapod,了解如何在一个NSDate上调用明天。这个pod的酷之处在于,它使用的是帮助国际化的区域,在那里,第二天可以从日落而不是中nite开始。

#1


49  

You should use Calendar method date(byAdding component:) to do your calendrical calculations and doing so you don't need to worry about those special cases:

您应该使用日历方法date(通过添加组件:)进行计算,这样您就不需要担心这些特殊情况:

extension Date {
    var yesterday: Date {
        return Calendar.current.date(byAdding: .day, value: -1, to: noon)!
    }
    var tomorrow: Date {
        return Calendar.current.date(byAdding: .day, value: 1, to: noon)!
    }
    var noon: Date {
        return Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
    }
    var month: Int {
        return Calendar.current.component(.month,  from: self)
    }
    var isLastDayOfMonth: Bool {
        return tomorrow.month != month
    }
}

Date().yesterday   // "Oct 28, 2017 at 12:00 PM"
Date()             // "Oct 29, 2017 at 12:54 PM"
Date().tomorrow    // "Oct 30, 2017 at 12:00 PM"

Date().yesterday.month   // 10
Date().isLastDayOfMonth  // false

#2


0  

I don't know if this helps you or not, but I would recommend not doing the math on NSDateComponents but rather on NSDate. Take a look at https://github.com/malcommac/SwiftDate a cocoapod for how to do things like call tomorrow on an NSDate. The cool thing about that pod is it uses Regions which helps for internationalization where the next day might start at sunset instead of mid nite.

我不知道这是否对你有帮助,但我建议不要在NSDateComponents上做数学运算,而是在NSDate上。看看https://github.com/malcommac/SwiftDate一个cocoapod,了解如何在一个NSDate上调用明天。这个pod的酷之处在于,它使用的是帮助国际化的区域,在那里,第二天可以从日落而不是中nite开始。