How to convert a full date to a short date in javascript?

后端 未结 8 1770
余生分开走
余生分开走 2020-12-13 23:40

I have a date like this Monday, January 9, 2010

I now want to convert it to

1/9/2010 mm/dd/yyyy

I tried to do this

    var startDat         


        
8条回答
  •  难免孤独
    2020-12-14 00:01

    Built-in toLocaleDateString() does the job, but it will remove the leading 0s for the day and month, so we will get something like "1/9/1970", which is not perfect in my opinion. To get a proper format MM/DD/YYYY we can use something like:

    new Date(dateString).toLocaleDateString('en-US', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
    })
    

提交回复
热议问题