Home > Net >  How to créate function that return a Date object similar to "Wed Dec 28 2022 11:36:25 GMT 0100&
How to créate function that return a Date object similar to "Wed Dec 28 2022 11:36:25 GMT 0100&

Time:12-28

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 or the substring() method.

2 - It must be indicated that the date is UTC and for this a Z must be added at the end. So, to properly convert a date like “01/12/2022” to a Date object, we must first change the format of the date and then add a Z to the end: “2022/12/01Z”.

3 - You have to do a "console.log() of the Date object created" and it should output something similar to "Wed Dec 28 2022 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 like this: "Wed Dec 28 2022 11:36:25 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:

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) {}

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(`${year}/${month}/${day}Z`);
  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.

  • Related