Increment a JavaScript date by one year and then decrement it by a day

After selecting a date from a vuetify date picker, I am attempting to reformat it as MM/DD/YYYY with an additional year and one less day. For example, January 1, 2022 should display as December 31, 2022. However, the code snippet I've written for this purpose is not functioning as expected:


formatDateNextYear(date) {
    if (!date) return null

    let a = new Date(date);

    a.setDate(a.getDate() - 1)
    a.setFullYear(a.getFullYear+1)

    const [year, month, day] = a.split('-')
    return `${month}/${day}/${year}`
}

The issue lies in the fact that the year isn't being added correctly and the formatting is inaccurate.

Answer №1

It slipped your mind to use the getFullYear function, but you can simplify the process by utilizing toLocaleDateString with the desired locale for formatting:

function formatNextYearDate(date) {
    if (!date) return null;

    let newDate = new Date(date);

    newDate.setDate(newDate.getDate() - 1);
    newDate.setFullYear(newDate.getFullYear() + 1);

    return newDate.toLocaleDateString("en-US");
}

console.log(formatNextYearDate(new Date("01/01/2022")));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to show input in Javascript HTML

Every time I try to run this code on my webpage, the buttons do not seem to respond when clicked. I am aiming to have the user input for full name, date of birth, and gender displayed in the text box when the display button is clicked. When the next butt ...

Implementing JavaScript functionality with CSS and HTML on a menu

I'm experiencing issues with my website's menu functionality. Currently, the submenu dropdown works fine, but the main menu is not functional. How can I enable it on the main menu as well? document.addEventListener('click', function( ...

WordPress admin-ajax.php not receiving Ajax call

Trying to implement AJAX in a WordPress admin submenu to call a function, I encountered the following issue: jQuery('#deleteProj').submit(ajaxSubmit); function ajaxSubmit(){ var tobeDeleted = jQuery(this).serialize(); alert(tobeDeleted); ...

Is there a way for me to incorporate a self-referencing onclick event into each <a> tag?

My single page app requires that link clicks are not processed in the regular way, but are instead passed to my router. I currently have a menu code that works perfectly (with the goto function changing the HTML and returning false): <a class="nav- ...

Conceal a Div Element on a Website

My website's home page features a CSS animation that slides two images with a high z-index off the screen to reveal the content below. I want this animation to only run the first time the page is accessed during a session, and not every time the user ...

Executing functions with directive controllers

Is there a simple way to call a function on a directive controller by accessing the instance using its id from the parent controller? <my-directive id="id1" /> var dirController = getDirectiveByID("id1"); dirController.someFunc(); If you have any ...

Issue with Material-UI Dialog Reusable Component: No error messages in console and app remains stable

Here is a component I've created for reusability: import { Dialog, DialogContent, DialogContentText, DialogTitle, Divider, Button, DialogActions, } from "@mui/material"; const Modal = ({ title, subtitle, children, isOpen, hand ...

Understanding the Relationship Between Interfaces and Classes in Typescript

I’ve come across an interesting issue while working on a TypeScript project (version 2.9.2) involving unexpected polymorphic behavior. In languages like Java and C#, both classes and interfaces contribute to defining polymorphic behaviors. For example, i ...

VueJS: Dynamically Change Events in FullCalendar Based on User Input

I have successfully set up fullcalendar in vuejs, displaying events for 3 members. Now I am looking to implement a feature that allows users to show or hide specific users' events with just a click. Although I have experience with jQuery, I am new to ...

Endless spirals within the confines of an angular controller

Every time I launch my app in a window, it gets caught in an endless loop where angular continuously calls the GameCtrl and ultimately freezes the window. Here is the code snippet causing the issue: index.html <!DOCTYPE html> <html ng-app="baseba ...

Error message: The call stack size limit has been exceeded only on Windows when running `npm start` in a server

While working on the serverless stack guide, I encountered a roadblock early on in Windows 10 (without any issues in Mac or Linux). I set up a basic serverless stack project and ran: npm run start And received this error: RangeError: Maximum call stack ...

Python tutorial: Scrape a website with a dropdown menu of ul-li items

Recently, I came across a query on how to scrape a particular website using Python that has a search box and javascripts. Intrigued by this question, I decided to try scraping company ratings from the website . The main goal was to input a company name in ...

What is the process for accessing the updated store states immediately after triggering an action in a component method?

I rely on Redux for managing state in my React JS application, but I am facing an issue with an event handler related to a button in my class component. Here is the code snippet: handleStartBtn = e => { const name = document.getElementById("n ...

Javascript Error - Issue with Fuse.js: e.split() function is not recognized

Scenario - I am in need of implementing a fuzzy search feature, and therefore utilizing fuse.js for this purpose. I obtained the code snippet from fuzzy.min.js at https://github.com/krisk/Fuse/blob/master/src/fuse.min.js Challenge - Despite using the cod ...

Tips for Re-positioning the Manage Password Window in a Browser Using CSS

I am facing an issue with the Caps Lock key indication on my login page. When the Caps Lock key is on, a tooltip should be displayed below the password field. However, when the browser's "manage passwords" bubbles are shown, the tooltip gets hidden be ...

Exploring a collection of objects in an Angular 2 component

Can someone please assist me in identifying what I am doing wrong or what is missing? I keep getting an undefined value for `this.ack.length`. this._activeChannelService.requestChannelChange(this.selectedchannel.channelName) .subscribe( ...

Align the position of two divs with matching IDs (#thumb-1 equals #project-1) using JavaScript or jQuery, but without the use of jQuery UI

I am currently working on creating a portfolio gallery and have put together the following HTML structure: <article class="work-gallery"> <ul> <li id="project-1"><img src="http://placehold.it/50x00"></li> ...

Is there a method to track the progress of webpage loading?

I am working on a website built with static HTML pages. My goal is to implement a full-screen loading status complete with a progress bar that indicates the page's load progress, including all images and external assets. Once the page has fully loaded ...

How can I display a specific element from a child Component when the main Component is clicked on in React?

I am currently working on my first React project and facing a challenge. I have a dropdown list on my main homepage that displays specific details when clicked. However, I am struggling to show the right corresponding detail (for example, black&white paren ...

Is it possible to set a variable to a specific value inside a callback function in JavaScript?

Currently, I'm working on developing a Chrome extension that focuses on conversions. However, I've hit a roadblock when it comes to retrieving data from storage. Below is the code snippet I'm currently using: var conversionFactor = 1; ...