简体   繁体   中英

How to convert a time string into UTC time string format in javascript

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.

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM