Formatting dates within text elements using code allows you to display dates dynamically and tailor them to different locales.
Use JavaScript's Date
class' toLocaleDateString
method to format dates on your site.
To render a date in the site visitor's locale settings on their computer, call toLocaleDateString()
on your date object without specifying any parameters. For example:
$w("currentDate").text = new Date().toLocaleDateString();
// Examples:
// en-US - 1/30/2025
// en-UK - 30/01/2025
Add parameters to customize the date's locale. For example:
const options = {
day: "numeric",
month: "short",
year: "numeric",
};
$w("currentDate").text = new Date().toLocaleDateString("en-US", options); // Jan 30, 2025
If you're displaying dates retrieved from a dataset, you can format all dates retrieved from your dataset in the same way using the dataset element's onReady()
and getCurrentItem()
with toLocaleDateString()
. For example:
$w("#myDataset").onReady(() => {
const date = $w("#myDataset").getCurrentItem().dateField;
// The dateText is linked to the dataset and is initially hidden.
$w("#dateText").text = new Date(date).toLocaleDateString();
$w("#dateText").show();
});
Note: You can also format dates from a dataset in the editor without code.