Home > Enterprise >  Reformatting date with Javascript
Reformatting date with Javascript

Time:04-28

(Updated for clarity!)

I need to implement a JS countdown timer through a rather inelegant solution and stumbled upon a particular challenge (I'm not a developer and out of my depth here).

On this page (https://jsbin.com/guxijofuca/edit?html,js,output) I want to extract the date from the HTML element, then apply/use it in the countdown plugin. However, the date exists in the following format: Apr 12, 2022 14:12

The plugin requires the code in this format:

// SET DATE TO SPECIFIC DAY IN THE FUTURE
// MONTHS go from 0 to 11: January is 0, February is 1, and so on
var then = new Date(2022, 11, 25, 15, 30, 0, 0);

Would someone be able to help me convert the above time into the format that's needed for the plugin?

CodePudding user response:

You only need assign that parsed countdown to a new Date class

var countDownDate = Date.parse(document.getElementById("goaltime").innerHTML);

const then = new Date(countDownDate);

console.log(countDownDate);
console.log(then);
<div id="goaltime">Apr 28, 2022 15:03</div>

The Date class actually can receive a single argument. There are many ways to make a new Date class object.

Some useful refrerences: W3Schools Date, MDN-Docs Date, and W3Schools Date parse()

CodePudding user response:

You've got a Date object already in countDownDate, why even bother creating that when you can set then to that value straight away?

var then = Date.parse(document.getElementById("goaltime").innerHTML);

This is assuming what you mentioned in your post is true and that the initial Date.parse operation doesn't return any exceptions based on the innerHTML content of the #goaltime element to the Date initially.

CodePudding user response:

You need to parse the string with Date.parse which returns the number of milliseconds since January 1, 1970. Then create a Date object with that.

const parsedDate = Date.parse(document.getElementById("goaltime").innerHTML);
const then = new Date(parsedDate);

If you need to alter the parsed date components at all you can break it down like this (adding or subtracting whatever you need to each component of the final new Date):

const parsedDate = Date.parse(document.getElementById("goaltime").innerHTML);
const tempDate  = new Date(parsedDate);
const then = new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate(), tempDate.getHours(), tempDate.getMinutes(), tempDate.getSeconds(), tempDate.getMilliseconds());

CodePudding user response:

You can use methods on Date to get year, month etc. Then pass these to plugin

//var dt = Date.parse(document.getElementById("goaltime").innerHTML);
const dt = new Date()

const year = dt.getFullYear();
const month = dt.getMonth();
const date = dt.getDate();
const hours = dt.getHours();
const mins = dt.getMinutes();

console.log({ year, month, date, hours, mins });

  • Related