Using JavaScript to find the weekday of the same date next year

Struggling to determine the weekday of a particular date next year? Take for example Tuesday, April 19, 2016 as the given date. What we need to calculate is: TUESDAY, April 18, 2017. Consistency with weekdays is crucial in this scenario.

The challenge lies in handling leap years. Help on this matter would be greatly appreciated.

$('.changeYear').click(function() {
        var appointments = [];
        for (var i = 1; i <= 22; i++) {
            var date = $('#tr-fix-tag-' + i).val();
            if (date !== "") {
                var splittedDate = date.substr(5).split('.');
                appointments.push(new Date(splittedDate[2], splittedDate[1] - 1, splittedDate[0]));
            }
        }

        var counter = 1;
        $.each(appointments, function() {
            var field = $('#tr-fix-tag-' + counter);
            var date = $(this)[0];
            var newDate = new Date(date.setFullYear(date.getFullYear() + 1));

            if (isSchaltjahr(newDate.getFullYear()))
                field.val(formatDate(new Date(newDate.setDate(newDate.getDate() - 2))));
            else
                field.val(formatDate(new Date(newDate.setDate(newDate.getDate() - 1))));

            counter++;
        });
    });

Answer №1

To keep the day the same when adding a year, you can adjust the resulting date by finding the nearest date with the same day of the week.

function sameDayNextYear(d) {
  // Duplicate the date
  var t = new Date(+d);
  // Get the current day number
  var startDayNum = d.getDay();
  // Add one year
  t.setFullYear(t.getFullYear() + 1);
  // Find the closest date with the same day number
  var diff = startDayNum - t.getDay();
  // If the difference is more than 3 days, subtract instead of add
  diff = (diff > 3) ? diff-7 : diff;
  t.setDate(t.getDate() + diff);
  return t;  
}

[new Date(2016, 1, 13), 
 new Date(2016, 1, 5),   
 new Date(2016, 1, 6),   
 new Date(2016, 1, 29),  
 new Date(2016, 2, 1)]   
 .forEach(function(d) {
  document.write(d + '<br>' + sameDayNextYear(d) + '<br><br>');
});

This method works for any day in any year, whether it's a leap year or not.

However, in some cases the resulting date may fall into the next or previous month (e.g. 2016-03-01 becomes 2017-02-28). To avoid this, you can compare the start and end months and adjust by a week to stay within the original month (for example, go back to 2017-03-07).

Answer №2

If I were to provide guidance, I would suggest following this code snippet and proceeding towards the desired date:

let DaysOfWeek=[
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
]

function DetermineDayOfWeek(year, month, day)
{
    let monthAdjustments = [ 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 ];
    year -= (month < 3) ? 1 : 0;
    let leapYears = Math.floor(year / 4);
    let gregorianYears = Math.floor(year / 100);
    let modernYears = Math.floor(year / 400);

    return DaysOfWeek[(year + leapYears - gregorianYears + modernYears + monthAdjustments[month - 1] + day) % 7];
}

Answer №3

This code was quickly put together to make it work, but there is room for optimization.

Feel free to check out the DEMO https://example.com/demo-link

The function aims to find the date of the same weekday next year by adding or subtracting days accordingly to get the closest match.

function findNextYearWeekday(currentDate)
{
  var weekDay = currentDate.getDay();
  var tempDate = new Date();
  tempDate.setFullYear(currentDate.getFullYear() + 1);
  
  var previousDays = 0;
  var nextDays = 0;

  // Check Previous Days
  for (var i = 0; i < 7; i++)
  {
    tempDate.setDate(currentDate.getDate() - i);
    if (weekDay == tempDate.getDay())
    {
      previousDays = i;
    }
  }

  // Reset the date
  tempDate = new Date();
  tempDate.setFullYear(currentDate.getFullYear() + 1);

  // Check Next Days
  for (var i = 0; i < 7; i++)
  {
    tempDate.setDate(currentDate.getDate() + i);
    if (weekDay == tempDate.getDay())
    {
      nextDays = i;
    }
  }

  // Reset the date
  tempDate = new Date();
  tempDate.setFullYear(currentDate.getFullYear() + 1);

  // Determine which date is closer
  if (previousDays < nextDays)
    tempDate.setDate(tempDate.getDate() - previousDays);
  else
    tempDate.setDate(tempDate.getDate() + nextDays);

  return tempDate;
}

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

"Keeping your HTML content up-to-date with AngularJS dynamic updates

I've noticed that when I upload changes to my AngularJS HTML partial files, there is a caching issue where the old data is displayed. It takes a few refresh actions before the changes become visible. Is there a way to make these changes appear immedi ...

The elements within the array are being refreshed accurately, however, a separate component is being removed

I have developed a component that has the ability to contain multiple Value components. Users can add as many values as they want, with the first value being mandatory and non-removable. When adding two new Value components, I provide input fields for name ...

The traditional function does not have access to a reference to this

For my web development project with Angular 9, I needed to add a typeahead feature using ng bootstrap typeahead. The code provided below worked perfectly: search = (text$: Observable<string>) => text$.pipe( debounceTime(150), disti ...

Stop the context menu from popping up when the element is right-clicked

Is there a way to create a custom right-click interaction for an element on my website, <div class="myElement"></div>? I want to avoid the default context menu from popping up when the user right-clicks on this element in order to enhance the u ...

Bizarre issue encountered while attempting to upgrade a program to Vue2

Upon running vue-migration-helper and updating everything, I encountered the error below. vue2.default.user is not a function Console error: Uncaught TypeError: _vue2.default.use is not a function at eval (eval at <anonymous> (app.js:1624), & ...

Developing an export feature for a mean application

Attempting to develop a basic module for organizing accounts on a website seemed like a straightforward task. I thought it would be as simple as creating a file with some functions, wrapping it in module.exports, and everything would work smoothly. However ...

Issue with ng-disabled not functioning properly for href tag within list item

Is there a way to prevent clicking on the <a> tag within a list item in a UI list so that the associated <div> is not displayed when clicked (excluding the last list item)? I have attempted using ng-disabled directly on the list item attribute ...

Updating a section of a component using another component

I need to update the Header.vue component from the ConfirmCode Component when the confirm method is called When a user logs in with axios ajax, I want to refresh the li element of the header component Appointment.vue: <send-sms-modal@clickClose="setS ...

Tips for formatting dates in Angular 6

I am currently working on a function that displays real-time dates based on user input. Currently, when the user enters the input, it is displayed in the front end as follows: 28.10.2018 10:09 However, I would like the date to change dynamically based on ...

The default zoom setting for ng-map is overly magnified when paired with the zoom-to-include-markers="true" feature

When using maps, I encountered an issue where having only one marker with the zoom-to-include-markers="true" attribute resulted in the map being overly zoomed in. Regardless of how I adjusted the zoom attribute, the result looked like this: https://i.sstat ...

In JavaScript, you can update the class named "active" to become the active attribute for a link

My current menu uses superfish, but it lacks an active class to highlight the current page tab. To rectify this, I implemented the following JavaScript code. <script type="text/javascript"> var path = window.location.pathname.split('/'); p ...

"Exploring the Power of Logarithmic Slider with Vue and Quasar

I'm currently working on a project utilizing Vue 2 and Quasar 1, where I am attempting to develop a logarithmic slider. Initially, I managed to create a basic example using a native input slider in this code pen: https://codepen.io/tonycarpenter/pen/Z ...

What is the significance of the underscore prefix in package.json properties?

Can you explain the significance of prefixing properties with an underscore in package.json? What is the reason behind using underscores in this context? "_from": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6b190e0a081 ...

Grouping geoJSON data on Mapbox / Leaflet

I am currently in the process of setting up a clustered map on mapbox, similar to the example shown here: At the moment, my point data is being extracted from MYSQL and then converted into GeoJson using GeoPHP. You can view the current map setup here. I ...

Turned off jquery on a specific div in order to resolve compatibility problems with Vue.js

Currently, I am working on a Drupal project which includes JQuery in all pages. We have recently introduced Vue.js for creating dynamic components directly in the HTML pages (not for building a single-page application). However, we are facing an issue whe ...

How to Create a Custom Callback Function for jQuery's .html

I am currently working with the following code: $.ajax({ type: 'GET', url: 'index.php?route=checkout/onepagecheckout/getpaypaldata', dataType: 'json', success: function(json) { ...

Searching for data between two specific dates can be achieved in Laravel Vue by utilizing the filter

I've successfully implemented a search feature for normal fields in my form. However, I'm encountering difficulty when trying to search within a date range. Here's my controller code: public function index() { $query = Matter::query(); $qu ...

Vue automatically refreshes momentjs dates prior to making changes to the array

I am dealing with a situation where my child component receives data from its parent and, upon button click, sends an event to the parent via an event bus. Upon receiving the event, I trigger a method that fetches data using a Swagger client. The goal is ...

Error message for Joi when validating a nested array of objects

I have received user input from the client side and am performing backend validation using Joi. const Joi = require("joi") const schema = Joi.array().items( Joi.object().required().keys({ name: 'filter_list', value: Joi.array(). ...

PHP code to display all the days between a specified date and the last day of the month

I definitely don't want to send back the DATE in the format Y-m-d. My goal is to display all the days up to the end of the month starting from a specific day regardless of the month or year. I attempted both [$array as $i] and [$array as $key], but ...