Save all user information annually from the date they first sign up

Greetings! I am facing an issue where every time a year is added, it gets inserted between the day and month in the date of entry for a user at our company.

var yearOnCompany = moment(user.fecha_ingreso_empresa, "YYYYMMDD").fromNow();
var dateStart = moment(user.fecha_ingreso_empresa).format("DD-MM-YYYY");
console.log(dateStart);
//03-12-2009
var f = parseInt(yearOnCompany);
var yearsOfWork = [];
for(var i = 1; i <= f; i++)
{
    dateStart = moment(dateStart, "DD-MM-YYYY").add(1, 'years').calendar();
    yearsOfWork.push(dateStart);
}
console.log(yearsOfWork);

Here is the result:

0:"12/03/2010"
1:"03/12/2011"
2:"12/03/2012"
3:"03/12/2013"
4:"12/03/2014"
5:"03/12/2015"
6:"12/03/2016"
7:"03/12/2017"

Answer №1

This issue seems to be a bit subtle! As per the moment docs, when using .calendar(), it defaults to a date format that may depend on the locale of the environment if no format is specified. In this case, it appears to default to MM/DD/YYYY instead of the preferred DD/MM/YYYY. Consequently, during the process, the dates may get swapped between month and day, causing confusion. To address this potential bug, consider converting dateStart from a string to a moment object as shown below:

var dateStart = moment(user.fecha_ingreso_empresa).format("DD-MM-YYYY");
var f = parseInt(yearOnCompany);
var yearsOfWork = [];
for(var i = 1; i <= f; i++)
{
    dateStart.add(1, 'years');
    yearsOfWork.push(dateStart.format("DD-MM-YYYY"));
}
console.log(yearsOfWork);

Answer №2

It seems like there might be an issue with the formatting here. Let me know if I am mistaken. Feel free to give this a try.

 for(var j = 1; j <= n; j++)
 {
   dateBegin  = moment(dateBegin , "MM-DD-YYYY").add(1, 'months');
   monthsOfService.push(dateBegin.format('MM-DD-YYYY'));
 }

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

Are you familiar with Mozilla's guide on combining strings using a delimiter in Angular2+?

I found myself in need of concatenating multiple string arguments with a specific delimiter, so after searching online, I stumbled upon a helpful guide on Mozilla's website that taught me how to achieve this using the arguments object. function myCo ...

rectangle/positionOffset/position().top/any type of element returning a position value of 0 within the container

While the height/position of the container is accurately displayed, attempting to retrieve the top position (or any position) of containing elements yields a return value of 0. Additionally, using .getBoundingClientRect() results in all values (top, left, ...

Tips for extracting popular song titles from music platforms such as Hungama or Saavn

I am looking to retrieve the names of the top trending songs/albums from platforms such as Hungama or Saavn. I experimented with web scraping packages available on npm to extract data from websites, including cheerio, jsdom, and request. Eventually, I came ...

Converting the given data into an object in JavaScript: a step-by-step guide

"[{'id': 3, 'Name': 'ABC', 'price': [955, 1032, 998, 941, 915, 952, 899]}, {'id': 4, 'Name': 'XYZ', 'id': [1016, 1015, 1014, 915, 1023, 1012, 998, 907, 952, 945, 1013, 105 ...

Importing components in real-time to generate static sites

My website has a dynamic page structure with each page having its unique content using various components. During the build process, I am statically pre-rendering the pages using Next.js' static site generation. To manage component population, I have ...

I'm sorry, but we were unable to locate the /bin/sh

After running a command using execSync that runs with sh, I observed the following: spawnSync /bin/sh ENOENT bin is now included in the PATH environment variable. Any ideas on this issue? ...

The presentation of the Google graph with dynamically changing data appears to be displaying inaccurately

I am looking to incorporate a graph displaying sales and purchase data on my webpage. Users should be able to select from categories like Purchase, Sales, or Production. I have separate tables for Purchase (AccPurchase) and Sales (AccSales), with productio ...

Automated logout feature will be enabled if no user interaction is detected, prompting a notification dialog box

Here is my working script that I found on this site. After a period of idle time, an alert message will pop up and direct the user to a specific page. However, instead of just the alert message, I would like to implement a dialog box where the user can ch ...

getStaticProps function in Next.js fails to execute

My [slug].js file includes two Next.js helper functions, getStaticPaths and getStaticProps. These functions are exported and create the path posts/[slug]. I have also added a post file named hello.json. However, when I try to access localhost:3000/posts/he ...

Adjusting the focus of an element with jQuery based on coordinates and offset values

jQuery.fn.getCoord = function(){ var elem = $(this); var x = elem.offset().left; var y = elem.offset().top; console.log('x: ' + x + ' y: ' + y); ); return { x, y }; }; This custom jQuery funct ...

Creating an Editor for Input Text Field in HTML: A Step-by-Step Guide

In the vast landscape of JS libraries that can achieve this function, like Trumbowyg and more. However, prior to my rails project displaying that slim version, I need to ensure JavaScript is properly escaped! Therefore, I need to create an editor using o ...

Obtaining Relative Values within Every Iteration using jQuery

I'm currently facing an issue with retrieving relative values within a .each() loop using jQuery. I have a set of table rows that contain a text input and a radio button each. My objective is to iterate through each row and save the value of the text ...

Increasing the Efficiency of Styled Components

It appears to me that there is room for improvement when it comes to checking for props in Styled Components. Consider the following code: ${props => props.white && `color: ${colors.white}`} ${props => props.light && `color: ${c ...

Chai-http does not execute async functions on the server during testing

In my app.js file, there is a function that I am using: let memoryCache = require('./lib/memoryCache'); memoryCache.init().then(() => { console.log("Configuration loaded on app start", JSON.stringify(memoryCache.getCache())); }); app.use( ...

When using node.js, the Ajax success function is not being executed

Why doesn't success respond? Here is the code I've used: Client-side code: function add(){ var values = formserial(addd); var tok = "abc", var url= 'http://localhost:8181/add'; $.ajax({ type: "POST", ...

Issues with FullCalendar.js failing to consistently fire when used in conjunction with JS/Ajax/ColdFusion

Attempting to troubleshoot an issue with FullCalendar.js integration on an external page called "calendar_summary.cfm", which is part of a series of pages reloading on a main page. The data from calendar_summary.cfm is transferred into FullCalendar.js thro ...

Leveraging document.getElementById alongside css modules

When trying to retrieve an element that is using a css module, I encountered a problem where the id of the element changes after rendering. As a result, document.getElementById("modal") returns null. import React from "react"; export const HandleClick = ...

Stop modal from closing in the presence of an error

My approach involves using a generic method where, upon adding a food item, a modal window with a form opens for the user to input their details. However, since backend validation for duplicate items can only be retrieved after the API call completes. I w ...

Tips for shortening extra text in a non-wrapping HTML table cell and adding "..." at the end

My HTML template includes text imported from a database field into a <td> tag. The length of the text can range from 3 to 200 characters, and the <td> spans 100% of the screen width. If the text surpasses the width of the screen, I want it to b ...

Error encountered in Express.js blogging app: Issue arises when attempting to filter posts by category, resulting in a "Cast to ObjectId failed" error

Currently, I am developing a blogging application using technologies like Express, EJS, and MongoDB. In the application, I have structured posts into different categories, each stored in its own collection. However, I encountered an issue while attemptin ...