Javascript date format not working correctly

Viewed 181

I changed the code. I have this function:

    function Date(stringDate){
        var date=moment(stringDate).locale('es').format('DD MMM');
        if(date=="Invalid Date"){
            return '-';
        } else {
            return date;
        }
    
    }

It still returns the date in english.

1 Answers

Note the caveats in the comments about this being the incorrect version for Spanish.

But if you still want to do this, using a regular expression replacement on the result of the above is probably the easiest. This is a slightly different formulation of your version, with that replace call added. It also allows you to supply the date, defaulting to today if one isn't supplied:

let formatDate = (date = new Date()) => date == "Invalid Date" 
  ? '-' 
  : date.toLocaleDateString('es-ES', {day: 'numeric', month: 'short'})
    .replace(/\b([a-z])/, (s, w) => w.toUpperCase())
    
console.log(formatDate())
console.log(formatDate(new Date(1776, 7, 4)))
console.log(formatDate(new Date(1862, 4, 5)))
console.log(formatDate(new Date('foo-bar-baz')))

Related