Home > database >  How to create function that return a Date object?
How to create function that return a Date object?

Time:12-29

1 - Make a function that given a date in text format "dd/mm/yyyy" returns a Date object with that date, using the Split() method.

2 - You have to do a "console.log() of the Date object created" and it should output something similar to

Mon Dec 2 2019 11:36:25 GMT 0100 (Central European Standard Time).

I have tried this but I don't know why when I write a console.log

I get the following: 2022-12-05T00:00:00.000Z

And I try to get it to appear something like this:

Mon Dec 2 2019 12:30:05 GMT 0100 (Central European Standard Time)

function convertDate(date) {
    let dateArray = date.split("/");
    let DateString = dateArray[2]   "/"   dateArray[1]   "/"   dateArray[0]   "Z";
    let dateDate = new Date(dateString);
    return dateDate;
}

console.log(convertDate("05/12/2022"));

CodePudding user response:

function convertDate(textDate) {
  const dateComponents = textDate.split('/');
  const day = dateComponents[0];
  const month = dateComponents[1];
  const year = dateComponents[2];

  const date = new Date(Date.UTC(year, month - 1, day));
  const timeZoneOffset = date.getTimezoneOffset() / 60;

  return date.toString("ddd MMM dd yyyy hh:mm:ss GMT"   timeZoneOffset)
}

console.log(convertDate("05/12/2022"));

Using moment js library can also help you providing you an easier solution to manipulate dates. I would highly suggest it.

CodePudding user response:

you can use new Date() to get the date like "Wed Dec 28 2022 11:36:25 GMT 0100"

let date = new Date("05/12/2022");
console.log(date);

output will be Thu May 12 2022 00:00:00 GMT 0500 (Pakistan Standard Time) {}

  • Related