Home > Software design >  Setting Time input format in Frontend
Setting Time input format in Frontend

Time:08-14

I'm trying to modify the below code in React Typescript. I want to return the input value in time format like - "Thu Jan 01 2022 13:03:00 GMT-0500 (Eastern Standard Time)" any suggestions how to do it?

Full Code: https://codepen.io/dcode-software/pen/jOwVqGO

function getTimeStringFromPicker(timePicker) {
    const selects = getSelectsFromPicker(timePicker);

    return `${selects.hour.value}:${selects.minute.value} ${selects.meridiem.value}`;
}

function numberToOption(number) {
    const padded = number.toString().padStart(2, "0");

    return `<option value="${padded}">${padded}</option>`;
}

activate();

CodePudding user response:

You can create a new Date object and set the hours and minutes on it. From there you get convert it to a string. Like this:

function getTimeStringFromPicker(timePicker) {
    const selects = getSelectsFromPicker(timePicker);
    const d = new Date();
    d.setMinutes(selects.minute.value);
    
    // setHours takes in hours in 24hr format
    if (selects.meridiem.value === "pm") {
        d.setHours(selects.hour.value   12);
    } else {
        d.setHours(selects.hour.value);
    }

    return d.toString();
}

If this solves your problem, you can mark it as correct.

CodePudding user response:

If you can reach a Date object somehow, its toLocaleString() method can do something like that (the actual parameters are described here.

let date = new Date();
console.log(date.toLocaleString("en-US", {
  timeZone: "EST",
  dateStyle: 'full',
  timeStyle: 'full',
  hour12: false // this is because you seem to want a 24-hour format
}));

If you need more, moment.js might be a library to check.

  • Related