0

I'm trying to render my date more pretty

It appeared like that : 2021-11-01T00:00:00.000Z

I wanna try to do dd/mm/yy

also my code :

<tr>
            <td type="text" id="montant" name="montant">
              {" "}
              {element.montant / 100}€
            </td>
            <td type="date" id="date" name="date">
              {" "}
              {element.date}
            </td>
</tr>
  • if it is a valid date just do this `new Date(element.date).toLocaleDateString()` – AngelSalazar Jan 13 '21 at 16:08
  • Try `new Date(element.date).toLocaleDateString('en-GB')` – User863 Jan 13 '21 at 16:09
  • use a date library it will ease the development when your project grows up, https://date-fns.org https://momentjs.com/ – Kalhan.Toress Jan 13 '21 at 16:11
  • 1
    Hello Wendy, changing how a date is rendered is often called formatting a date. You can find a lot of examples in [this thread](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – Lars Jan 13 '21 at 16:13

4 Answers4

2

Try this:

let date = new Date();

console.log(date.toLocaleDateString())
sonEtLumiere
  • 3,656
  • 3
  • 4
  • 24
1

You can use external libraries such as D3, moment.js or date-fns.

If you really don't want to use any external libraries, you can try the following code:

Date.prototype.format = function(fmt) { 
     var o = { 
        "M+" : this.getMonth()+1,                
        "d+" : this.getDate(),          
        "h+" : this.getHours(),            
        "m+" : this.getMinutes(),          
        "s+" : this.getSeconds(),                
        "q+" : Math.floor((this.getMonth()+3)/3), 
        "S"  : this.getMilliseconds()          
    }; 
    if(/(y+)/.test(fmt)) {
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
    }
     for(var k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
         }
     }
    return fmt; 
}
// Then you can format the date object by:
console.log(new Date().format("yy/MM/dd")) // return: 21/01/14
Jannchie
  • 106
  • 8
0

you can try like this

<tr>
            <td type="text" id="montant" name="montant">
              {" "}
              {element.montant / 100}€
            </td>
            <td type="date" id="date" name="date">
              {" "}
              {new Date(element.date).toLocaleDateString()}
            </td>
</tr>
Kiran B
  • 55
  • 6
0

I recommend the moment.js bookstore. With it you can do date formatting without too much hassle. Ex: const myFormatDate = moment (myDate) .format ('DD / MM / YYYY')

https://momentjs.com/docs/#/parsing/string-format/