Home > OS >  How to change the time format from HH:MM to 2023-01-25T19:15:27.615Z in React Js
How to change the time format from HH:MM to 2023-01-25T19:15:27.615Z in React Js

Time:01-27

Basically, the most scenarios of programming in react js. The conversion of time is from this 2023-01-25T19:15:27.615Z to HH:MM. So, here in my scenario I want to make the vice versa of it.

CodePudding user response:

within moment you can do this by telling moment the format you are providing for instance moment('13:00', 'HH:mm'); is valid and the return object can be converted to ISO string with .toISOString()

CodePudding user response:

You can use date-fns library. Firstly install npm install date-fns

import {format} from 'date-fns'


...
format(new Date(),'HH:mm') // MM for months you have to use mm

CodePudding user response:

An external library is not needed to set the hours and minutes for the current date and get an ISO string — a simple function will work:

function timeToIsoString (
  hoursMinutes,
  { date = new Date(), utc = false } = {},
) {
  const [h, m] = hoursMinutes.split(":").map(Number);
  const d = new Date(date.getTime());
  d[utc ? "setUTCHours" : "setHours"](h);
  d[utc ? "setUTCMinutes" : "setMinutes"](m);
  return d.toISOString();
}

const input = "12:34";

// Interpreting time in local time zone:
const output1 = timeToIsoString(input);
console.log(output1);

// Interpreting time in UTC:
const output2 = timeToIsoString(input, { utc: true });
console.log(output2);

// Starting with an existing date:
const date = new Date(Date.UTC(2008, 8, 15));
const output3 = timeToIsoString(input, { date, utc: true });
console.log(output3); // "2008-09-15T12:34:00.000Z"

  • Related