Method 1: Using toLocaleDateString()
Solution
To get the current date without time in react js, you can use the .toLocaleDateString()
function which can have the power to format date based on the country and much more.
Snippet
In this snippet, we will see multiple short example of using toLocaleDateString()
to get date without time.
const date = new Date();
// Convert the date to a string in the desired format
const dateString1 = date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
console.log(dateString1) // December 12, 2022
const dateString2 = date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'numeric',
day: 'numeric'
});
console.log(dateString2) // 12/12/2022
console.log(dateString2.replace(/\//g, '-')) // 12-12-2022
Example
In this example, we will use .toLocaleDateString()
method to get date without time and show in the react UI.
Let’s start coding…
import React from "react";
export default function App() {
const date = new Date();
const dateString = date.toLocaleDateString("en-US", {
year: "numeric",
month: "numeric",
day: "numeric"
});
console.log(dateString); // 12/12/2022
return (
<div className="App">
<h1>{`Current Date without time`}</h1>
<p>{dateString}</p>
</div>
);
}
Output
Links
Method 2: Using get separate year, month, and date
Solution
To get the current date without time in react js, you can use the .getFullYear()
, .getMonth()
, and .getDate()
methods and format in your desired format.
Snippet
In this snippet, we will see short example to use the .getFullYear()
, .getMonth()
, and .getDate()
methods and format the date without time.
const date = new Date();
const dateString = `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}-${date.getFullYear()}`;
console.log(dateString) // 12-12-2022
Example
In this example, we will use the .getFullYear()
, .getMonth()
, and .getDate()
methods to get date without time and show in the react UI.
Let’s start coding…
import React from "react";
export default function App() {
const date = new Date();
const dateString = `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}-${date.getFullYear()}`;
console.log(dateString); // 12-12-2022
return (
<div className="App">
<h1>{`Current Date without time`}</h1>
<p>{dateString}</p>
</div>
);
}
Output