0

I have a date coming back in this format 2021-12-03T00:00:00.000Z which I then convert to an ISO date string and then construct a new Date() based on the split ISO string. The issue is that my date properly gets formatted with every month except December. Anytime I pass a December date, the logic always converts it to be January of the next year.

Code

//bill.date_paid at this point = '2021-12-03T00:00:00.000Z'

let isoDateString = new Date(bill.date_paid).toISOString().split('T')[0].split('-');

//isoDateString = ['2021', '12', '03'];

bill.date_paid = new Date(isoDateString[0], isoDateString[1], isoDateString[2]).getTime();

//date conversion above = 1641193200000 which is equal to a January date... 

But why?

Nick is tired
  • 6,860
  • 20
  • 39
  • 51
CodeConnoisseur
  • 1,452
  • 4
  • 21
  • 49
  • Why is `isoDateString` an array with the individual date components and not an ISO-8601 formatted string! – phuzi Nov 03 '21 at 15:02
  • 1
    `isoDateString[1]` is a 1-indexed month (as a string). `Date(year, month, day)` takes a zero-indexed month (as a number). – Heretic Monkey Nov 03 '21 at 15:38

3 Answers3

3

To convert your iso date to the mm/dd/yyyy format you can use a Intl.DateTimeFormat object like below :

const date = new Date('2021-12-03T00:00:00.000Z');
const result = new Intl.DateTimeFormat('en-US').format(date);
console.log(result);
dariosicily
  • 4,239
  • 2
  • 11
  • 17
1

You can try this

date = new Date('2021-12-03T00:00:00.000Z');    
console.log((date.getMonth()+1)+'/'+(date.getDate()) + '/'+date.getFullYear());

Also you can use moment.js

console.log(moment(new Date('2021-12-03T00:00:00.000Z')).format("MM/DD/YYYY"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Dave
  • 494
  • 6
  • 21
1

Why you don't convert it directly to time?

let date_paid = '2021-12-03T00:00:00.000Z'
let date = new Date(date_paid).getTime()
console.log(date)
NiceToMytyuk
  • 3,644
  • 3
  • 39
  • 100