Home > Software design >  How to convert a date from Spanish to English Using Javascript?
How to convert a date from Spanish to English Using Javascript?

Time:12-24

var a = new Date('dic 30, 2021').toLocaleString("en-US", {
    weekday: "long",
    year: "numeric",
    month: "short",
    day: "numeric"
});

--> returns 'Invalid Date'

I want to do this in Javascript

CodePudding user response:

To be sure that new Date(string) give us a date object we need the string was in the way yyyy-MM-dd. So you need make a "trasform" function, some like

  spaToDate(datespa:string)
  {
    const part=datespa.replace(',','').split(' ')
    return new Date( part[2],
      ['ene','feb','mar','abr','may','jun','jul','ago',
       'sep','oct','nov','dic'].indexOf(part[0]),
       part[1]
      )
  }

CodePudding user response:

In javascript Date class dic is not a valid month name, you need to change it to dec,

enter image description here

vs

enter image description here

  • Related