Home > Back-end >  How to get a Date object from a 12 hour time string
How to get a Date object from a 12 hour time string

Time:07-26

I am trying to provide a default value for a TimePicker object. But the that value I have is a string e.g "12:00 PM" And the picker needs a Date object.

I tried parsing the time directly into a Date object like shown below, but it does not work

let startTime = new Date("12:00 PM");

How can i convert this time string into a Date object so that i can provide the default value to the TimePicker.

CodePudding user response:

Ive been able to create a function that can do the conversion, since I did not find any solution to this.

const dateFromTime = ({ timeString }) => {
    const dateTime = new Date();
    let timeHours = parseInt(timeString.substring(0, 2));
    let timeMinutes = parseInt(timeString.substring(3, 5));
    let timeAMPM = timeString.substring(6,
    if (timeAMPM === "PM") {
        timeHours  = 12;

    dateTime.setHours( timeHours, timeMinutes, 0, 0);
    return dateTime;
}
const dateTime = dateFromTime({ timeString: "12:00 PM" });

This get the current date and time and instead sets the time to the specified time. and returns that

For any improvements, please suggest the right way to do this.

CodePudding user response:

HTML:

<input id="appt-time" type="time" name="appt-time" value="13:30">

JS

const timeFrom12hto24h = time12h => {
  const [time, meridiem] = time12h.split(" ");
  let [hours, minutes] = time.split(":");
  if (hours === "12") hours = "00";
  if (meridiem === "PM") hours = parseInt(hours, 10)   12;
  return {hours, minutes}
};

const getMyObjectTime= timeFrom12hto24h('12:00 PM');

// apply the time to the HTML element
document.getElementById("appt-time").value = getMyObjectTime.hours   ':'   getMyObjectTime.minutes;

// one way to generate the needed time object
const dateInMiliseconds = new Date().setHours(getMyObjectTime.hours, getMyObjectTime.minutes, 0)
console.log(dateInMiliseconds);

In case there is moment.js already used in the project it would be like this:

HTML:

<input id="appt-time" type="time" name="appt-time" value="13:30">

JS:

// apply the time to the HTML element
document.getElementById("appt-time").value = moment("01:00 PM", 'hh:mm A').format('HH:mm')

// one way to generate the needed time object
let [hour, minutes] =  moment("01:00 PM", 'hh:mm A').format('HH,mm').split(',');
const dateInMiliseconds = new Date().setHours(hour,minutes, 0)
console.log(dateInMiliseconds);

CodePudding user response:

I used date-and-time package to format current time. It's worked for me.

npm install date-and-time

Controller

const date = require("date-and-time");

const now = new Date();
const startTime = date.format(now, "HH:mm:ss");
  • Related