What’s up everyone, Hoping to get some help on an issue regarding some date formatting.
We have a page that we’re going to use as a way to display a quick summary of blog posts based on a custom dataset: https://saidareales.wixsite.com/fidi-2018/events-2 . The page actually works as expected, but we’re running into an issue trying to format the date.
We found this article: https://support.wix.com/en/article/using-wix-code-to-format-dates which is supposed to help us format the date into a nicer format, however when we run the code we get an error saying "TypeError: Cannot read property ‘toLocaleDateString’ of undefined”.
When I try to debug and just console.log the $w(‘#dataset1’).getCurrentItem, it comes back as null. It seems like it thinks there’s no items in the dataset even though the information displays properly.
Any help would be greatly appreciated,
-Dave M
You should have something like this. Do not connect your text to you database directly , instead do it with code.
$w("#repeater1").onItemReady( ($w, itemData, index) => {
var options = { weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'};
let date = itemData.yourDate
$w("#text1").text=date.toLocaleDateString('en-US', options)
});
Hi Dave,
@carlosgalvarez has a point. First, you have to disconnect the date text from Data. Second, use the code to format the date for every item of your repeater:
$w.onReady(() => {
$w("#repeater1").onItemReady(($item, itemData) => {
$item("#text34").text = itemData.date.toLocaleDateString("en-US");
});
});
Hey guys,
Thanks for the help. I was able to use the code from both of your examples to come up with a solution. It turns out that there was a hidden issue with the error. The text takes some time to change from when its ready vs when the content for the date and time is swapped out for the text. Here is the code that I ended up using to get everything working:
setTimeout(function() {
$w("#repeater1").onItemReady(($item, itemData) => {
let dateOptions = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
};
let timeOptions = {
hour: 'numeric',
minute: '2-digit'
}
let date = itemData.date;
let dateString = date.toLocaleDateString('en-US', dateOptions);
let timeString = date.toLocaleTimeString('en-US', timeOptions);
$item("#text34").text = dateString + " at " + timeString;
});
}, 500);
Thanks again for your help
Hey Dave,
You haven’t disconnected the texts from Data. That’s why the data connection overrides the manually formatted value.
Just disconnect the text from Data and you won’t need the hack with setTimeout
. To do that, select the text, click on “Connected to Data” button that looks like a green database, in the opened panel (“Connect Text”) open “Connect a dataset” dropdown, choose the first option (namely, “Choose”), and close the panel.