Home > Software design >  How to convert a time string into UTC time string format in javascript
How to convert a time string into UTC time string format in javascript

Time:12-19

I have a 24 hour time looks like 14:00 and I want to convert this into today's utc time string format which is looks like Mon Dec 19 2022 14:00:00 GMT 0530 (India Standard Time). How can I do this in javascript.

CodePudding user response:

That isn't UTC, that's local time in India.

The output looks like the now-defined¹ output of the Date toString method, so you need to:

  1. Create a Date instance for today with 14:00 as the time (local time).
  2. Use toString

// Your time string
const time = "14:00";
// Split it into hours and minutes as numbers
const [hours, minutes] = time.split(":").map(Number);
// Get a date for "now"
const dt = new Date();
// Set its hours, minutes, seconds, and milliseconds
dt.setHours(hours, minutes, 0, 0);
// Get the string
const str = dt.toString();

console.log(str);

For me here in England that outputs Mon Dec 19 2022 14:00:00 GMT 0000 (Greenwich Mean Time), but for someone in India it should output something in that time zone.


¹ For a very long time, the output of toString wasn't precisely defined. As of recent specifications, it is.

CodePudding user response:

You can use the Date object and the toUTCString method.

const timeString = "2022-12-19T14:30:00";
const date = new Date(timeString);
const utcTimeString = date.toUTCString();
console.log(utcTimeString); // "Tue, 20 Dec 2022 00:30:00 GMT"
  • Related