Solution
To convert date to UTC in React, use toISOString()
method it will convert date to UTC and return utc date string.
To format a date you can read my below article, here I have explained multiple ways to format a date.
https://reactjssnippet.com/posts/how-to-display-date-in-react-js/
Snippet
In this snippet, we will see short example to convert date into utc date.
// Current Date to UTC Date
const ISOdate = new Date().toISOString();
console.log("Current Date to UTC: ", ISOdate) // Current Date to UTC: 2022-12-29T13:42:30.665Z
// specific date to UTC Date
const spcDate = new Date("2022-12-28 01:15:00").toISOString();
console.log("specific Date to UTC: ", spcDate) // specific Date to UTC: 2022-12-27T19:45:00.000Z
Example
In this example, we will write a react js code to convert date into UTC date and show in the React UI.
Let’s list down what we are going to do below example.
- Create
utcDate
state - Convert current date into UTC date and set in state ( useEffect )
- Show UTC date into React UI
import React, { useState, useEffect } from "react";
export default function App() {
const [utcDate, setUtcDate] = useState("");
useEffect(() => {
const date = new Date();
setUtcDate(date.toISOString());
}, []);
return (
<div className="App">
<h1>Current Date into UTC date</h1>
<p>{utcDate}</p>
</div>
);
}
Output