Skip to content Skip to footer

How to Turn Back Time by Subtracting Days from Dates in JavaScript

Alright, fellow code wranglers, let’s dive into a task that’s as common as it is crucial: manipulating dates and times in JavaScript. Whether you’re building a booking app or setting up a reminder feature, at some point, you’ll need to play with dates. Today’s challenge? Subtracting days from a given date. Let’s roll up our sleeves and get coding!

The Vanilla JS Way: Subtract Days Like a Time Lord

In pure JavaScript, subtracting days from a date is a piece of cake. We’re going to create a date, then travel back in time by subtracting days. Check this out:

const subtractDays = (date, daysToSubtract) => {
  const result = new Date(date);
  result.setDate(result.getDate() - daysToSubtract);
  return result;
};

// Usage
const today = new Date();
console.log(`Today is: ${today.toDateString()}`);

const daysAgo = subtractDays(today, 5);
console.log(`Five days ago was: ${daysAgo.toDateString()}`);

This little snippet defines a function that takes a date and the number of daysToSubtract. It creates a new Date object to avoid mutating the original date (always a good practice), then uses setDate() and getDate() to perform the time travel.

React’s Temporal Twist: Subtract Days in a Component

React developers, you’re up! Let’s integrate our time-traveling function into a React component. We’ll use the power of hooks to keep our UI up-to-date with the selected date.

import React, { useState } from 'react';

const TimeTraveler = () => {
  const [selectedDate, setSelectedDate] = useState(new Date());

  const subtractDaysFromCurrent = (days) => {
    setSelectedDate((currentDate) => {
      const result = new Date(currentDate);
      result.setDate(result.getDate() - days);
      return result;
    });
  };

  return (
    <div>
      <p>Selected Date: {selectedDate.toDateString()}</p>
      <button onClick={() => subtractDaysFromCurrent(5)}>
        Go Back 5 Days
      </button>
    </div>
  );
};

export default TimeTraveler;

In this component, we’re rocking a useState hook to manage our date state. The subtractDaysFromCurrent function takes care of the math, and we’ve got a button to trigger the time travel on demand. Neat, huh?

Vue’s DeLorean: Computed Properties and Methods

Vue.js enthusiasts, we haven’t forgotten about you. Let’s build a Vue instance with a method to subtract days and a computed property to display the result.

<template>
  <div>
    <p>Current Date: {{ currentDate }}</p>
    <p>Last Week: {{ lastWeekDate }}</p>
    <button @click="subtractDays(7)">Last Week</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentDate: new Date().toDateString(),
    };
  },
  methods: {
    subtractDays(days) {
      const result = new Date(this.currentDate);
      result.setDate(result.getDate() - days);
      this.currentDate = result.toDateString();
    },
  },
  computed: {
    lastWeekDate() {
      return this.subtractDays(7);
    },
  },
};
</script>

In our Vue app, we’ve got a method subtractDays that adjusts our currentDate. We’re also using Vue’s reactivity system to automatically update the UI whenever currentDate changes. The computed property lastWeekDate provides a handy way to display the date from a week ago without recalculating it every time it’s accessed.

Alright, that’s the first half of our time-traveling journey through JavaScript dates. We’ve covered the basics in vanilla JS and how to integrate the concept into React and Vue. Stay tuned for the second half, where we’ll explore subtracting days in Angular, using date-fns for those fancy utility functions, and more!

Angular’s Time Machine: Services and Pipes

Angular developers, it’s your time to shine. We’ll create a service to handle date operations and a pipe to format the date in any component effortlessly.

First up, the service:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DateService {
  subtractDays(date: Date, days: number): Date {
    const result = new Date(date);
    result.setDate(result.getDate() - days);
    return result;
  }
}

This DateService is injectable, meaning you can use it across your Angular app. It has a subtractDays method that does exactly what you expect – takes a Date object and a days number, and returns a new Date object.

Now, let’s use this service in a component:

import { Component } from '@angular/core';
import { DateService } from './date.service';

@Component({
  selector: 'app-time-travel',
  template: `
    <p>Today is: {{ today | date }}</p>
    <p>A week ago was: {{ lastWeek | date }}</p>
    <button (click)="goBackAWeek()">Travel Back a Week</button>
  `
})
export class TimeTravelComponent {
  today: Date = new Date();
  lastWeek: Date;

  constructor(private dateService: DateService) {
    this.goBackAWeek();
  }

  goBackAWeek() {
    this.lastWeek = this.dateService.subtractDays(this.today, 7);
  }
}

In the TimeTravelComponent, we’re utilizing our DateService to set lastWeek to a date that’s seven days in the past. We’re using Angular’s built-in date pipe in the template for formatting.

Date-fns: The Time Traveler’s Toolkit

For those who want to keep their codebase lean and avoid reinventing the wheel, date-fns provides a treasure trove of date utility functions. Let’s see how to subtract days with date-fns.

First, install date-fns if you haven’t already:

npm install date-fns

Then, use it in your code like so:

import { subDays } from 'date-fns';

const today = new Date();
console.log(`Today is: ${today.toDateString()}`);

const fiveDaysAgo = subDays(today, 5);
console.log(`Five days ago was: ${fiveDaysAgo.toDateString()}`);

The subDays function from date-fns is self-explanatory – it subtracts the specified number of days from the given date. It’s clean, it’s simple, and it doesn’t mutate the original date.

Luxon: DateTime Manipulation with Style

If you’re looking for something a bit more robust than date-fns, Luxon by the creators of Moment.js is a fantastic library for date manipulation. Let’s see it in action:

First, add Luxon to your project:

npm install luxon

And then use it to subtract days:

import { DateTime } from 'luxon';

const today = DateTime.now();
console.log(`Today is: ${today.toISODate()}`);

const fiveDaysAgo = today.minus({ days: 5 });
console.log(`Five days ago was: ${fiveDaysAgo.toISODate()}`);

Luxon’s DateTime object is rich with methods for date manipulation. The minus method is particularly handy for subtracting not just days, but also weeks, months, and even years.

Moment.js: The Old Guard

Moment.js has been the go-to library for date manipulation in JavaScript for years. Though it’s now considered a legacy project in favor of newer libraries, it’s still widely used.

Here’s how to subtract days with Moment.js:

const moment = require('moment');

const today = moment();
console.log(`Today is: ${today.format('YYYY-MM-DD')}`);

const fiveDaysAgo = today.subtract(5, 'days');
console.log(`Five days ago was: ${fiveDaysAgo.format('YYYY-MM-DD')}`);

Moment makes it straightforward with the subtract method. Despite its size and the recommendation to use newer libraries, Moment.js remains a powerful tool for date manipulation.

And there you have it, folks – a comprehensive guide to subtracting days from dates in JavaScript, covering vanilla JS, React, Vue, Angular, and popular date manipulation libraries. Whether you’re building the next big event planning app or simply automating a “days since last incident” counter, you now have the tools to handle dates like a pro. Keep coding, and may your time-travel adventures be bug-free!