Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract date components?

As today is Friday, which is 6 according to NSCalendar. I can get this by using the following

Calendar.current.component(.weekday, from: Date())

How do I get weekday component of Saturday last week, which should be 7?

If I do Calendar.current.component(.weekday, from: Date()) - 6 . I am getting 0 which is not valid component.

like image 581
Coder221 Avatar asked Dec 30 '16 10:12

Coder221


People also ask

How do you subtract days from a date?

Therefore, you can add or subtract days as easy as adding or minus the number of days in Excel. 1. Select a blank cell you will place the calculating result, type the formula =A2+10, and press the Enter key. Note: For subtracting 10 days from the date, please use this formula =A2–10.

What are the components of a date?

A date or time specified in terms of units (such as year, month, day, hour, and minute) to be evaluated in a calendar system and time zone.

How do you minus days from date in JS?

To subtract days to a JavaScript Date object, use the setDate() method. Under that, get the current days and subtract days. JavaScript date setDate() method sets the day of the month for a specified date according to local time.

Can you subtract dates in Swift?

To subtract hours from a date in swift we need to create a date first. Once that date is created we have to subtract hours from that, though swift does not provide a way to subtract date or time, but it provides us a way to add date or date component in negative value.


2 Answers

Try this, you have to get the date first then subtract again from it:

var dayComp = DateComponents(day: -6)
let date = Calendar.current.date(byAdding: dayComp, to: Date())
Calendar.current.component(.weekday, from: date!)
like image 88
Tj3n Avatar answered Oct 13 '22 00:10

Tj3n


For that first you need to get that date using calendar.date(byAdding:value:to:) and then get day number from it.

extension Date {
    func getDateFor(days:Int) -> Date? {
         return Calendar.current.date(byAdding: .day, value: days, to: Date())
    }
}

Now simply use thus function and get your days.

if let date = Date().getDateFor(days: -6) {
    print(Calendar.current.component(.weekday, from: date))
}
like image 44
Nirav D Avatar answered Oct 12 '22 23:10

Nirav D