简体   繁体   中英

Javascript setting date format including 0 with date and month

Essentially I am trying to convert a date such as 2019-02-09 to 09-02-2019. I have the following:

var newDate = new Date('2019-02-09');
strDate = newDate.getDate() + "-" + (newDate.getMonth() + 1) + "-" + newDate.getFullYear();

which works but will output 9-2-2019. Is there a neat method (ie not checking getDate and getMonth less than 10) to get the output 09-02-2019?

Using toLocaleDateString() :

 var dt = new Date('2019-02-09'); var x = dt.toLocaleDateString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit' }) .replace(/[^0-9]/g, '-'); console.log(x); 

Just use the toLocaleDateString() method and choose en-GB as the locale to return your date in the DD/MM/YYYY format and use a simple split() and join() or regex to replace / with - like this:


Split and Join approach:

 var newDate = new Date('2019-02-09'); strDate = newDate.toLocaleDateString('en-GB').split("/").join("-"); alert(strDate); 


Regex:

 var newDate = new Date('2019-02-09'); strDate = newDate.toLocaleDateString('en-GB').replace(/[^0-9]/g, '-'); alert(strDate); 

You could use padStart to achieve your goal.

 var newDate = new Date('2019-02-09'); strDate = newDate.getDate().toString().padStart(2, "0") + "-" + (newDate.getMonth() + 1).toString().padStart(2, "0") + "-" + newDate.getFullYear(); console.log(strDate); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM