Format the date coming out from dataset on a repeater

Hello guys,

I had a lot of bugs trying to do this on a dynamic page but didn’t turn out great :frowning: when I figure that out I’ll share it too

Today i’ll show you the code to format the dates coming (Parsing?) out of your collection/datset. Yes I know wix already has one but it isn’t as perfect as you would like it.


But there’s a an ever better way to make it look like this:

Here’s the code:

export function dataset1_ready() {
 // This function was added from the Properties & Events panel. To learn more, visit http://wix.to/UcBnC-4
 // Add your code for this event here: 
 $w('#repeater1').onItemReady(($item, itemData, index) => {
 let currentItem = $item('#dataset1').getCurrentItem()
 let dateFromCollection = currentItem._createdDate
  let dateFromQuery = new Date(dateFromCollection);
// get the current time
var now = new Date();
// calculate the difference
var queryTimeStamp = (dateFromQuery).getTime();
var nowTimeStamp = now.getTime();
var microSecondsDiff = Math.abs(queryTimeStamp - nowTimeStamp);
console.log("msecs diff: " + microSecondsDiff);
// Number of milliseconds in a day:
//   24 hrs/day * 60 mins/hr * 60 secs/min * 1000 msecs/sec
var daysDiff = Math.floor(microSecondsDiff/(1000 * 60 * 60 * 24));
console.log("days diff: " + daysDiff);
var hoursDiff = Math.floor(microSecondsDiff / (1000 * 60 * 60));
console.log("minutes diff: " + minsDiff);
var minsDiff = Math.floor(microSecondsDiff / (1000 * 60));
console.log("minutes diff: " + minsDiff);
if ( minsDiff < 59) { //minute
 if ( minsDiff < 1) {
    $item("#textTypeDate").text = type + "Just now"// says just now before 1 min reaches
   }else{
       $item("#textTypeDate").text = minsDiff + "m ago"// says how many minutes + m ago after 1 min to 
       }
}else{
 if ( minsDiff > 59) {//hours ago
   $item("#textTypeDate").text = hoursDiff + "h ago"
    }
 if ( minsDiff > 1439) {//days ago
    $item("#textTypeDate").text = daysDiff + "d ago" 
        }
 if ( minsDiff > 43800) {//last month
    $item("#textTypeDate").text = "Last month" 
        }
 if ( minsDiff > 87599) {//more than 1 month (2 months and above)
 const options = {
       month: "long",
       day: "numeric",
    };  
    $item("#textTypeDate").text =  dateFromCollection.toLocaleDateString("en-US", options);
 if ( minsDiff > 525600) {//years
 const options2 = {
        day: "numeric",
        month: "short",
        year: "numeric"
};
 // Sets the property of the text element to be a string representing today's date in US English
    $item("#textTypeDate").text = dateFromCollection.toLocaleDateString("en-US", options2);
        }
}
   });
}

The code looks long but it’s actually very simple. Get current locale time and doing the math to get the date the item was parsed (added)

example the item was put 72739380 milliseconds convert it to minutes (≈ 1,212) then calculate how many minute in a day, month, 2 month and year and input it there idk lol but that’s how I got it

You’re welcome

Please know you can also tweak these to your liking

If you have any bugs or errors or maybe even ideas. Please email me at nzubefootballer@gmail.com or you can create a new forum and tag me

DJ bon26

2 Likes

Hi me again :slight_smile:

Like I explained in your other contribution , there are tools already build for processing time in javascript. One of the most known is Moment.js

here is how to use it

import moment from "moment" // don't forget to install the package
 
$w('#repeater1').onItemReady(($item, itemData, index) => {
 let currentItem = $item('#dataset1').getCurrentItem()
 let dateFromCollection = currentItem._createdDate
 
  $item("#textTypeDate").text = moment(dateFromCollection).fromNow()
}

Pretty convenient isn’t it? :slight_smile:

again those tools have been battle test by and an army of developers all around the world and bring many more feature

I realize this post is 2 years old, BUT I just wanted to say THANK YOU! I had been trying to do exactly this and tried so many other codes that people had posted here and this one was the only one that worked for me. It might be longer than the others - but oh, so effective :slight_smile: Thanks a bunch!

Hi I’m glad I helped someone out :slight_smile:

There’s even a better way to do this. I extracted the function out to make the code look clean.

function formatDate(date) {
    let dateFromQuery = new Date(date);
    var now = new Date();
    var queryTimeStamp = (dateFromQuery).getTime();
    var nowTimeStamp = now.getTime();
    var microSecondsDiff = Math.abs(queryTimeStamp - nowTimeStamp);
    var daysDiff = Math.floor(microSecondsDiff / (1000 * 60 * 60 * 24));
    var hoursDiff = Math.floor(microSecondsDiff / (1000 * 60 * 60));
    var minsDiff = Math.floor(microSecondsDiff / (1000 * 60));
    if (minsDiff < 59) { //minute
        if (minsDiff < 1) {
            return `Just now` // says just now before 1 min reaches
        } else {
            return `${minsDiff}m ago` // says how many minutes + m ago after 1 min to 
        }
    } else {
        if (minsDiff > 525600) { //years
            const options = {
                day: "numeric",
                month: "short",
                year: "numeric"
            };
            // Sets the property of the text element to be a string representing today's date in US English
            return `${date.toLocaleDateString("en-US", options)}`
        }
        if (minsDiff > 87599) { //more than 1 month (2 months and above)
            const options = {
                month: "long",
                day: "numeric",
            };
            return `${date.toLocaleDateString("en-US", options)}`
        }
        if (minsDiff > 43800) { //last month
            return `Last month`
        }
        if (minsDiff > 1439) { //days ago
            return `${daysDiff}d ago`
        }
        if (minsDiff > 59) { //hours ago
            return `${hoursDiff}h ago`
        }
    }
}

export function dataset1_ready(){
    $w('#repeater1').onItemReady(($item, itemData, index)=>{
        const createdDate = itemData._createdDate
        $item("#textTypeDate").text = formatDate(createdDate) //Now you can format any date easily by passing it inside the formatDate()
    });
}

Hopefully this helps,
Brendan Okey-iwobi

Nice! I will try that out. I’ll be making another post shortly with something I’m struggling on and will tag you in it. Hopefully you can help me out with that too!

Hi Kentin!
When I use this code, all items in the repeater have the same “time ago” which seems to be based on the first item. Do you know if there’s a way to fix this?

Hi,

check if you used this “$w” instead of “$item”