-2

I have a backend responding with this date format, when i use it with date object in javascript, i get an error saying "Uncaught SyntaxError: Invalid or unexpected token"

how can i get date from it in DD/MM/YYYY:MM:SS ?

new Date(2021-01-27T14:29:22.723782Z)
c137
  • 65
  • 5
  • Formatting *might* have been [asked before](https://stackoverflow.com/search?q=%5Bjavascript%5D+how+to+format+a+date) (about 4,500 times apparently). – RobG Mar 09 '21 at 07:20

2 Answers2

1

Add quotations "" or '': new Date('xxxxxx')

const targetDate = new Date('2021-01-27T14:29:22.723782Z');
console.log(targetDate);

function formatDate(d) {
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const date = String(d.getDate()).padStart(2, '0');
  const hr = String(d.getHours()).padStart(2, '0');
  const min = String(d.getMinutes()).padStart(2, '0');
  const sec = String(d.getSeconds()).padStart(2, '0');

  return `${date}/${month}/${year} ${hr}:${min}:${sec}`;
}

console.log(formatDate(targetDate));
Description JS Remarks
Year .getFullYear()
Month .getMonth() January -> 0
Date .getDate()
Hours .getHours()
Minutes .getMinutes()
Seconds .getSeconds()
Convert a value to a string String(xxxx)
A length of a string becomes 2. If an original strings shorter than 2, 0 fills the length .padStart(2, '0') '98'->'98' / '2' -> '02'

Another solution

const targetDate = new Date('2021-01-27T14:29:22.723782Z');
console.log(targetDate);

function formatDate(d) {
  const options = {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false,
    timeZone: 'America/Los_Angeles'
  };
  
  return new Intl.DateTimeFormat('id-ID', options).format(d).replace(/\./g, ':');
}

console.log(formatDate(targetDate));
Miu
  • 846
  • 8
  • 22
1

Input to Date should be string here.

new Date("2021-01-27T14:29:22.723782Z") // Wed Jan 27 2021 19:59:22 GMT+0530 (India Standard Time)

And to format date, you can look for moment.js library or can do it manually.

Refer this answer: Javascript format date / time

Naresh J
  • 2,087
  • 5
  • 26
  • 39