Joseph
Joseph

Reputation: 7785

Convert DateTime to Date in ES6

I'm trying to convert this value 2020-06-16T02:55:08.151437Z to Date using this function below. How can i convert this correctly using the best and efficient way possible? If possible no packages please

FUNCTION

export function getParsedDate(date) {
  date = String(date).split(' ');
  const days = String(date[0]).split('-');
  const hours = String(date[1]).split(':');
  return [
    parseInt(days[0]),
    parseInt(days[1]) - 1,
    parseInt(days[2]),
    parseInt(hours[0]),
    parseInt(hours[1]),
    parseInt(hours[2]),
  ];
}

JSX

{getParsedDate(order.date)}

Upvotes: 0

Views: 10165

Answers (3)

kapil pandey
kapil pandey

Reputation: 1903

I also don't like using libraries for every tasks that can be easily done without library.Here are some of the in-build JS methods that you must give a try:

let date1=new Date("2020-06-16T02:55:08.151437Z").toDateString()
console.log(date1)

let date2=new Date("2020-06-16T02:55:08.151437Z").toUTCString()
console.log(date2)

let date3=new Date("2020-06-16T02:55:08.151437Z").toLocaleDateString()
console.log(date3)

let date4=new Date("2020-06-16T02:55:08.151437Z").toLocaleDateString('en-US', {
month: '2-digit',day: '2-digit',year: 'numeric'})
console.log(date4)

let date5=new Date("2020-06-16T02:55:08.151437Z").toString()
console.log(date5)

let date6=new Date("2020-06-16T02:55:08.151437Z").toLocaleString()
console.log(date6)

Upvotes: 4

Subesh Bhandari
Subesh Bhandari

Reputation: 1122

You can use Javascript native Date constructor

new Date('2020-06-16T02:55:08.151437Z')

In jsx,

{new Date('2020-06-16T02:55:08.151437Z').toString()}

Check out for formatting patterns in docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toString

Upvotes: 1

Shivanshu Gupta
Shivanshu Gupta

Reputation: 324

You can use this popular library known as moment.js while working with dates:
Documentation:
https://momentjs.com/docs/

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

To get days and hours from the date, you can follow this link:
https://momentjs.com/docs/#/get-set/day/

Solution:

const d = "2020-06-16T02:55:08.151437Z";
const convertedDate = moment(d).format("DD-MM-YYYY");
console.log(convertedDate);

So, using this library you can convert date to almost any supported format.

Upvotes: 0

Related Questions