Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a date with "nd","rd", "th" into a yyyy-mm-dd format Javasciript

Tags:

javascript

I have an array of dates like:

dates=['2nd Oct 2014','20th Oct 2014','20th May 2019']

and I want to return them as an array in the YYYY-MM-DD format. so far I have this:

function formatDate(dates) {
var t=[];
dates.map(function(date){
 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;
    t.push([year, month, day].join('-'));
});
console.log(t);


    return t;
}
var dates = ['2nd Oct 2014','20th Oct 2014','20th May 2019']
 console.log(formatDate(dates));

but this gives me :

[NaN-NaN-NaN,NaN-NaN-NaN,NaN-NaN-NaN]

since its not able to recognize the date with "th", "nd".any idea how to fix this so that I get the o/p as:

[2014-10-02,2014-10-20,2019-05-20]

here is the fiddle: http://jsfiddle.net/nakpchvf/

Thanks!

like image 217
user1234 Avatar asked Jan 20 '26 10:01

user1234


2 Answers

If you're using moment, or if using it is an option, it's fairly simple:

const dates=['2nd Oct 2014','20th Oct 2014','20th May 2019'];

dates.forEach(date => {
  console.log(moment(date, 'Do MMM YYYY').format('YYYY-MM-DD'));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
like image 151
ic3b3rg Avatar answered Jan 22 '26 23:01

ic3b3rg


Just remove letters.

function formatDate(dates) {
var t=[];
dates.map(function(date){
    let datePieces = date.split(' ');
    datePieces[0] = datePieces[0].replace(/\D+/g, '');
    var d = new Date(datePieces.join(' ')),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

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


    return t;
}
var dates = ['2nd Oct 2014','20th Oct 2014','20th May 2019']
 console.log(formatDate(dates));

Basically above I take each date and split it into 3 different parts. I then fix the first index (the one causing an issue) by removing any non-numerical characters. After that I can recombine to form your date string :).

like image 27
basic Avatar answered Jan 23 '26 01:01

basic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!