Search code examples
javascriptarraysloopsdateepoch

How to change date and filter data due to the month when each date is saved in different way?


I have an array of dates:

["Mon Dec 17 2018 16:36:04 GMT+0100 (Central European Standard Time)", 1545064594, 1545294858, "Thu Dec 20 2018 09:37:16 GMT+0100 (Central European Standard Time)", 1545306111, 1545310335, "Thu Dec 20 2018 12:46:48 GMT+0100 (Central European Standard Time)", 1545319619, 1545742063, 1545918029, 1546602411, 1546602745, 1546957949]

as you can see each date is written differently....I would like to make an if statement - that if value length is equal to epoch length then the date should to be changed... so far I wrote this code:

 const Month = [];
 for (let i = 0; i < database.length; i++) {
 Month.push(database[i].date);
  }
 console.log(Month);


  if (Month == 18){
  console.log(Month.length)


  var utcSeconds = Month
  var d = new Date(0); 
  d.setUTCSeconds(utcSeconds);
  console.log (d)

}

I got the dates and array and also the Epoch code works...but my problem is that not all of them are Epoch dates so I'm confused how to go trough that...and later I still would like to filter data and separate it for Dec / Jan as 2 separate arrays ( I need this data for dashboard ). I will appreciate any help.


Solution

  • The numerical values seem to be time since epoch in seconds, you could convert all the values in the array to Date objects using something like this:

    let arr = ["Mon Dec 17 2018 16:36:04 GMT+0100 (Central European Standard Time)", 1545064594, 1545294858, "Thu Dec 20 2018 09:37:16 GMT+0100 (Central European Standard Time)", 1545306111, 1545310335, "Thu Dec 20 2018 12:46:48 GMT+0100 (Central European Standard Time)", 1545319619, 1545742063, 1545918029, 1546602411, 1546602745, 1546957949];
    
    
    arr = arr.map(v => {
      if (!isNaN(v)) {
        v *= 1000; // from seconds to milliseconds
      }
      return new Date(v);
    })
    
    console.log(arr.map(v => v.toString()));