Generating a collection of timestamps for dates with a yearly increment

Consider pulling the minimum date as 1420070400000, which corresponds to 2015-01-01 00:00:00, and the maximum date as 1575158400000, which translates to 2019-12-01 00:00:00.

Next, establish an array of timestamps for each month between those two dates using this script:

var offset = 5*60*60000

dtMin = new Date(+1420070400000 + offset);
dtMax = new Date(+1575158400000 + offset);

console.log("dtmin: ", dtMin);
console.log("dtmax: ", dtMax);

while (dtMin <= dtMax) {

  dtRng.push((dtMin.getTime() - offset).toString());

  dtMin = new Date(new Date(dtMin).setMonth(dtMin.getMonth()+1));

}

console.log("dt rng:", JSON.stringify(dtRng));

The resulting array looks like this:

["1420070400000","1422748800000","1425168000000","1427842800000","1430434800000","1433113200000","1435705200000","1438383600000","1441062000000","1443654000000","1446332400000","1448928000000","1451606400000","1454284800000","1456790400000","1459465200000","1462057200000","1464735600000","1467327600000","1470006000000","1472684400000","1475276400000","1477954800000","1480550400000","1483228800000","1485907200000","1488326400000","1491001200000","1493593200000","1496271600000","1498863600000","1501542000000","1504220400000","1506812400000","1509490800000","1512086400000","1514764800000","1517443200000","1519862400000","1522537200000","1525129200000","1527807600000","1530399600000","1533078000000","1535756400000","1538348400000","1541026800000","1543622400000","1546300800000","1548979200000","1551398400000","1554073200000","1556665200000","1559343600000","1561935600000","1564614000000","1567292400000","1569884400000","1572562800000","1575158400000"]

However, sometimes it includes a 31-day or 30-day interval such as:

Epoch date  Human readable date (GMT) 
1420070400  2015-01-01 00:00:00
1422748800  2015-02-01 00:00:00
1425168000  2015-03-01 00:00:00
1427842800  2015-03-31 23:00:00
1430434800  2015-04-30 23:00:00
1433113200  2015-05-31 23:00:00
1435705200  2015-06-30 23:00:00
1438383600  2015-07-31 23:00:00

If you're incrementing by month, why is this happening?

Moreover, keep in mind that minDate and maxDate can fluctuate. For example, minDate could be 1464739200000 (Wed, 01 Jun 2016 00:00:00) while maxDate might be 1488326400000 (Wed, 01 Mar 2017 00:00:00)...

Also, why does it work correctly for the initial 3 months but not thereafter? The behavior seems erratic...

---EDIT-----

Considering using moment.js for this purpose, you can update the while section with the following code:

   while (dtMin <= dtMax) {

       dtRng.push(dtMin);

       dtMin = moment(dtMin).add(1, 'months').toDate();
       console.log("dtmin: ", dtMin);
   }

An unexpected outcome occurs here...the console displays:

Sun Feb 01 2015 00:00:00 GMT-0500 (EST)
Sun Mar 01 2015 00:00:00 GMT-0500 (EST)
Wed Apr 01 2015 00:00:00 GMT-0400 (EDT)
Fri May 01 2015 00:00:00 GMT-0400 (EDT)
Mon Jun 01 2015 00:00:00 GMT-0400 (EDT)
Wed Jul 01 2015 00:00:00 GMT-0400 (EDT)
Sat Aug 01 2015 00:00:00 GMT-0400 (EDT)
Tue Sep 01 2015 00:00:00 GMT-0400 (EDT)

Nevertheless, the timestamps pushed to dtRng look different, showing 30th and 31st days with 23 hours:

Epoch date  Human readable date (GMT) 
1422748800  2015-02-01 00:00:00
1425168000  2015-03-01 00:00:00
1427842800  2015-03-31 23:00:00
1430434800  2015-04-30 23:00:00
1433113200  2015-05-31 23:00:00
1435705200  2015-06-30 23:00:00
1438383600  2015-07-31 23:00:00
1441062000  2015-08-31 23:00:00
1443654000  2015-09-30 23:00:00

The expected output should appear like this:

Epoch date  Human readable date (GMT) 
1422748800  2015-02-01 00:00:00
1425168000  2015-03-01 00:00:00
1427846400  2015-04-01 00:00:00
1430438400  2015-05-01 00:00:00
1433116800  2015-06-01 00:00:00
1435708800  2015-07-01 00:00:00
1438387200  2015-08-01 00:00:00
1441065600  2015-09-01 00:00:00

Answer №1

It appears that there is a time zone complication where transitioning from Eastern Standard Time (EST) to Eastern Daylight Time (EDT) results in either losing or gaining an hour, leading to the display of 23:00:00 for certain dates.

While handling time zones can be tricky, I recommend a straightforward solution for this issue by generating all dates in UTC using the Date.UTC function. A simple loop can be implemented to iterate through each month for every year:

for(var year = 2015; year < 2020; year++)
    for(var month = 0; month < 12; month++)
        dtRng.push(new Date(Date.UTC(year, month, 1, 00, 00, 00)));

The output obtained from

console.log(JSON.stringify(dtRng))
provides accurate results:

"2015-02-01T00:00:00.000Z",
"2015-03-01T00:00:00.000Z",
"2015-04-01T00:00:00.000Z",
"2015-05-01T00:00:00.000Z",
"2015-06-01T00:00:00.000Z",
....

An adjustment could involve segmenting the loop into three parts for start and end dates:

  • For the initial year, loop through months starting from the specified month to December.
  • For all years except the final one, loop through all twelve months.
  • For the last year, loop through January to the ending month.

The following code demonstrates this logic for a date range (2015/03/01 to 2019/09/01) formatted as YYYY/MM/DD.

// Setting up the date range.
var startYear = 2015, startMonth = 03,
      endYear = 2019,   endMonth = 09;

// Iterating through the years.
for(var year = startYear; year <= endYear; year++) {
    var currStartMonth = 1, currEndMonth = 12;

    // Skipping months before the date range in the initial year.
    if (year === startYear) currStartMonth = startMonth;

    // Skipping months after the date range in the final year.
    // This also handles cases when startYear is equal to endYear.
    if (year === endYear)     currEndMonth = endMonth;

    // Looping through months and adding them to the dates array.
    // '- 1' is used due to the zero-based indexing of months.
    for (var month = currStartMonth - 1; month < currEndMonth; month++) 
        dtRng.push(new Date(Date.UTC(year, month, 1, 00, 00, 00)));
}

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

If it contains multiple strings, then perform this action; otherwise, do that

Looking to create a script that prompts for additional information (group Id) if there are SCOM groups with the same names: function myFunction { [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [string[]]$ObjectName ) ...

NodeJS - The function app.listen is not defined in this context

I've come across a similar question before, but the answers provided didn't help me resolve my issue. The error message I'm getting is "TypeError: app.listen is not a function"; Here's my full code below. Thank you in advance for your ...

Issue with Vue 3 where radio input remains unchecked after being clicked

I'm currently facing an issue with radio buttons for answers in my questions. Whenever I click on an answer, the radio input does not stay checked and I am unable to disable the other options. My front-end is developed using Vue 3 and the back-end wit ...

Having issues executing the JavaScript bindings for selenium WebDriver

I am currently utilizing the Python selenium binding and would like to explore the JavaScript binding, but I am facing difficulties with the sample application. I am unable to pinpoint the issue in this example, so any assistance would be greatly appreciat ...

Tips for executing both onclick events and a href links simultaneously

boilerPlate.activityStream = "<div class='socvid-aspect-ratio-container'>"+ "<div onclick='com.ivb.module.home.pics.showDialogBox(\"{%=nodeId%}\",\"{%=class ...

Detecting collisions in JavaScript

Currently, I am in the process of reviving an old game reminiscent of Tron using HTML5 canvas and JavaScript. The unique twist in this version is that the snakes have the ability to move in curves rather than right angles (known as Achtung Die Kurve). The ...

Error encountered: MongoDB cast exception - nested subdocument

Check out this schema design: var messageSchema = new Schema({ receivers: [User], message: String, owner: { type: Schema.Types.ObjectId, ref: 'User' } }); var userSchema = new Schema({ name: String, photo: String }); var in ...

Exploration and Organizing Tool

When searching for elements multiple times using the Enter key, the search filter is not being applied properly. It works fine when searching one at a time. For example, if I search for the letter 'A' in a specific column, the output should displ ...

Guide to setting up a new user in Sanity with their profile pictures

Hey there, I am new to working with Sanity and currently tackling a personal project. My main query is regarding how to add a user along with their profile image (uploaded as a file from their device) to the Sanity Database. I need all the details entered ...

Is there a way to generate an OSRM file using geojson information?

I am in possession of a geojson datafile that contains paths labeled as highway=footway, and I am interested in utilizing OSRM for finding routes between multiple points (similar to the travelling salesman problem rather than just the most direct route fro ...

When using `parseInt` on the string "802.11 auth", the result did not match my expectations

I am developing a data parser that transforms the output of a command into a JSON object for sending to a live logging and graphing platform. All data extracted by the parser is returned as strings, but I need numerical values to be preserved as numbers. H ...

Generating a component of a structure array by utilizing a function that takes a pointer to the structure

Struggling to create a function that modifies a struct array with pointer. Want the array to have an additional struct element after calling this function. Here's the revised version of my function based on your advice: void addPic(pic *picture_Reco ...

Uncertain as to why the if statement is failing to recognize whether the operand is an object or not

In the query below, you will find a snippet of code: console.log("returnAnonModel -----", returnAnonModel, "typeof : ", typeof returnAnonModel). This code indicates that returnAnonModel is an object. However, it's puzzling why the if-else conditions a ...

What is the process for incorporating a dropdown field and editable field within a container?

Looking to create a unique setup by incorporating dropdown fields and editable text fields within a designated box, similar to the image provided. Any tips on how to successfully implement this design? https://i.sstatic.net/6tGMp.jpg ...

Two approaches for one single object

I'm trying to figure out why this particular code works // ....................................................... var character = { name: 'Joni', type: 'blond', sayName: function() { return this.name; }, sayT ...

Tips for Providing Real-Time Data for a Dynamic Chart in d3

I have a line chart sample from D3, and the issue I'm facing is that I need to continuously feed live data from a server at certain time intervals and use D3 to draw the chart based on this dynamic data. Despite my efforts to search for a solution, I ...

Accessing external content within our webpage

Previously, I utilized iframes to display an external page within our asp.net page. However, I have now decided to explore alternative methods that do not involve iframes. My goal is to open an external page within our page using only a simple aspx page wi ...

Pressing the button is causing the Kendo Angular ToolBar Overflow button to refresh the page

Currently, I am using the Kendo Angular toolbar. As users resize the screen, an overflow button becomes visible. However, upon clicking this button, the page refreshes and appears to be performing a post back. Below is the code snippet: <kendo-toolbar ...

Steps to eliminate the specified element from the rear end of an array

If I know that the "array_pop" function can be used to remove the last element from an array, but what if I wanted to remove the last 2 or 3 elements instead? Could you please explain how I would go about removing the last 2 elements from the following ar ...

What is the method for transforming an array object into an object?

How can I assign the values of an array object called hello to a constant called answer, changing the key value in the process? I've considered using Object.entries but couldn't quite get it right. Is there a way to achieve this? Here is my cod ...