1

Tried to convert date format but not working. my input is 23th Oct 2054 output shoud be like 2054-10-23. How to do it in javascript? my code is not working.

function formatDate(date) {
  var m = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  var d = new Date(date),
    month = '' + (d.getMonth() + 1),
    day = '' + d.getDate(),
    year = d.getFullYear();

  if (month.length < 2)
    month = '0' + month;
  if (day.length < 2)
    day = '0' + day;

  return [year, month, day].join('-');
}

var dates = ["23th Oct 2054", "29th Jul 2014", "12th May 2054", "20th Jun 2050", "23th Dec 2059"];

var results=formatDate(dates);

console.log(results.join('\n'),+'\n');

output should be

2054-10-23  
2014-07-29  
2054-05-12 
2050-06-20 
2059-12-23
kayu s
  • 13
  • 4
  • And after the "ver" fix, doubt you'll get desired results with `23th Oct 2054` – GetSet Jan 23 '21 at 19:11
  • @GetSet: Not working – kayu s Jan 23 '21 at 19:12
  • 2
    Someone commented on making "ver" to "var". And you did so. But unfortunately for some unknown reason, you also decided to pass in array of dates to your function that doesn't work on arrays. – GetSet Jan 23 '21 at 19:13
  • @GetSet:How to get solution? – kayu s Jan 23 '21 at 19:15
  • "DDth Mmm YYYY" is not a format that `new Date()` accepts, some reading tells me it needs to be a a string that is able to be understood by a `Date.parse()`, otherwise I believe you need a time library or manually parsing it yourself and re arrange it. `Date.parse("23th Oct 2054") is NaN` – ajax333221 Jan 23 '21 at 19:16
  • @ajax333221: Someone did in different language but i do not know how to write in javascript..if you know pls help me:https://stackoverflow.com/questions/54309166/how-to-change-date-string-format-20th-oct-2052-2052-10-20 – kayu s Jan 23 '21 at 19:18
  • Your input date is stored in an array which you are submitting to your function, but your function is expecting a single string. – Tangentially Perpendicular Jan 23 '21 at 19:39

7 Answers7

1

Here is a dirty regex solution that does not use the Date object:

function formatDate(date) {
  var newDates = date.map((item) => {
    var m = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var day = item.match(/\d+/)[0];
    day = day < 10 ? "0" + day : day;
    var month = m.indexOf(item.match(/\s([A-Za-z]{3})\s/)[1]) + 1;
    month = month < 10 ? "0" + month : month;
    var year = item.match(/\d{4}$/)[0];
    return `${year}-${month}-${day}`;
  });
  return newDates;
}

var dates = ["23th Oct 2054", "29th Jul 2014", "12th May 2054", "20th Jun 2050", "23th Dec 2059"];
console.log(formatDate(dates));
Wais Kamal
  • 5,858
  • 2
  • 17
  • 36
1

In your example, you are passing an array into your function when it is expecting a string. You are also getting an invalid date object because Date does not accept your format.

Date will accept an ISO Date (2054-10-23), a short date (10/23/2054), or a long date (Oct 23 2054). Your format is very close to the "long date" format.

By removing the "-th", "-nd" or "-st" from your dates, it becomes an accepted long date format which you can pass when initializing a new Date:

new Date(date.replace(/th|nd|st/, ""));

Your function works as intended now (assuming you are passing in a string instead of an array).

Cleaned up example:

function formatDate(date) {
  const dateObj = new Date(date.replace(/th|nd|st/, ""));
  let year = dateObj.getFullYear();
  let month = dateObj.getMonth() + 1;
  let day = dateObj.getDate();

  if (month.length < 2) month = "0" + month;
  if (day.length < 2) day = "0" + day;

  return [year, month, day].join("-");
}

var dates = ["23th Oct 2054", "29th Jul 2014", "12th May 2054", "20th Jun 2050", "23th Dec 2059"];
dates.forEach(date => console.log(formatDate(date)));

I recommend using date-fns or moment when working with dates. Formatting them becomes much easier!

Sem
  • 11
  • 1
0

Uh, I just did it manually

function formatDate(date) {
  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  [d,m,y]=date.split(' ');
  d=d.split('').filter(a=>!isNaN(a)).join('');
  return [y,m,d].join('-');
}

var dates = ["23th Oct 2054", "29th Jul 2014", "12th May 2054", "20th Jun 2050", "23th Dec 2059"];

dates.forEach(a=>console.log(formatDate(a)))
The Bomb Squad
  • 4,192
  • 1
  • 9
  • 17
0

In one word, MOMENT! :)

If you can get rid of the -th, -rd on the day number, you can use this great library (which is extremely flexible and useful). -> https://momentjs.com/

var dates = ["23 Oct 2054", "29 Jul 2014", "12 May 2054", "20 Jun 2050", "23 Dec 2059"];

console.log(dates.map(date => moment(date, 'DD MMM YYYY').format('YYYY-MM-DD')));
<script src="https://momentjs.com/downloads/moment.js"></script>
<div id='html'></div>
0

The first problem is that you're passing an array to a function that doesn't accept an array. Secondly you're passing an invalid date format to Date().

This doesn't use Date(). It just assumes the last 4 digits are the year, the first 1-2 digits are the day, and that the month is in the middle. Case insensitive and whole month is allowed in date format.

function formatDate(date) {
  var m = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
  var month = String(m.indexOf(date.split(/[\s-]/)[1].slice(0, 3).toLowerCase())+1),
    day = date.split(/[^0-9]/)[0],
    year = date.slice(-4);
    
  if (month.length < 2)
    month = '0' + month;
  if (day.length < 2)
    day = '0' + day;

  return [year, month, day].join('-');
}

;
for (var dates = ["23th Oct 2054", "29th Jul 2014", "12th May 2054", "20th Jun 2050", "23th dec 2059"], i=0; i<dates.length; i++) {
    console.log(formatDate(dates[i]));
}
PHP Guru
  • 1,301
  • 11
  • 20
0

You can use the below code for this.

var dates = ["23th Oct 2054", "29th Jul 2014", "12th May 2054", "20th Jun 2050", "23th Dec 2059"];
console.log(formatDate(dates));


function formatDate(date) {
  var mainArr = [];
   if(!Array.isArray(date)) {
      date = [date];
   }
   for(i=0;i<date.length;i++) {
        var dateVal = date[i];
        var dateValArr = dateVal.split(' ');
        var filterDateArr = [];
        for(j=0;j<dateValArr.length;j++) {
          var val = dateValArr[j]
          if(j==0) { 
            var val = dateValArr[j].replace(/\D/g, ""); 
          }
          filterDateArr.push(val);
        }
        var filterDate = filterDateArr.join(' ');
        var d = new Date(filterDate),
            month = '' + (d.getMonth() + 1),
            day = '' + d.getDate(),
            year = d.getFullYear();

        if (month.length < 2) {
            month = '0' + month;
            }
        if (day.length < 2) {
            day = '0' + day;
            }
            mainArr.push([year, month, day].join('-'));
      }
   return mainArr;
}
Amit Saini
  • 575
  • 4
  • 11
0

You are passing array to function and operating on single item, also invalid string is passed to Date object. Check out below code

function formatDate(dates) {
var result=[]
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
for (i = 0; i < dates.length; i++) {
    [d,m,y]=dates[i].split(' ');
    day=d.slice(0,d.length-2)
    month = (months.indexOf(m)+1).toString();
    year = y;

    if (month.length < 2)
      month = '0' + month;
    if (day.length < 2)
      day = '0' + day;
    result.push([year, month, day].join('-'));
}
return result;
}

var dates = ["23th Oct 2054", "29th Jul 2014", "12th May 2054", "20th Jun 2050", "23th Dec 2059"];
console.log(formatDate(dates));
Kuroko
  • 11
  • 1