0

I have one function that gives the date, the only problem is that my date is displayed like this on 5/31/2021, but I want to make it appear on 05/31/2021 here is my code

<span>{{ dtFormatter(course.updated_at) }}</span>

dtFormatter(d) {
  var dateObj = new Date(d);
  var day = dateObj.getUTCDate();
  var month = dateObj.getUTCMonth() + 1; //months from 1-12
  var year = dateObj.getUTCFullYear();
  return day + "." + month + "." + year;
},
Synchro
  • 1,105
  • 3
  • 14
  • 44
  • 1
    `new Date().toLocaleDateString('en-UK').replaceAll('/', '.')` – Hassan Imam Jun 26 '21 at 11:12
  • @HassanImam gave you a one-liner code to solve your problem, but in your question - you are asking on how to show it with slashes '/', but in your code you are returning with dots '.' - If it should be with slashesh, just use the @Hassan's code, without the `replaceAll` function like so: `new Date().toLocaleDateString('en-UK')` – aspirinemaga Jun 26 '21 at 11:18

4 Answers4

1

You can use padStart to add a leading Zero if needed:

day.padStart(2, '0') + '.' + month.padStart(2, '0') + '.' + year

day and month should be a string btw

Shahroozevsky
  • 343
  • 4
  • 17
1

I see you already calculated the day. so you can do this.

`0${day}`.slice(-2)`

this will output 01~09 and 10~31.

Dan Robert
  • 55
  • 8
0

You can use String#slice to add a leading 0 if needed:

('0' + day).slice(-2) + '.' + ('0' + month).slice(-2) + '.' + year;

Note: padStart doesn't work in IE.

Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • I didn't downvoted yet, but your variables aren't declared in your answer, so if I copy and paste it, it won't work – aspirinemaga Jun 26 '21 at 11:12
0

As mentioned by @HassanImam, you could use a one-liner code:

new Date().toLocaleDateString('en-UK')

otherwise:

const date = new Date()
const m = String(date.getMonth() + 1).padStart(2, '0')
const d = String(date.getDate()).padStart(2, '0')
const y = String(date.getFullYear())

const formatedDate = [m, d, y].join('/')

console.log(formatedDate)
aspirinemaga
  • 3,753
  • 10
  • 52
  • 95