Working with dates and time in WIX Code?

Wayne (and anyone else who needs it) … here’s what I ended up with (it works!!)

  1. Show a date from my database
  2. Calculate a date X days after the original start date, and show that on the page as well
  3. Format both dates to read as Month Date, Year (“April 20, 2018”)

Note: you can format the date any way you need by making a few changes to the line:
// formats date to Month Date, Year
var expDate = longMonth + " " + day + ", " + year;

Here’s the first part of the CODE →

(This goes into data.js in the backend)
export function Members_afterQuery(item) {
item.expDate = setMemberExpDate(item._createdDate);

return item;

function setMemberExpDate(_createdDate) {
var originalDate = new Date(_createdDate);
var date = new Date(originalDate);

// set expiration 1 year 
date.setDate(date.getDate() + 364); 

const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; 

const day = date.getDate().toString(); 
const longMonth = monthNames[date.getMonth()]; 
const year = date.getFullYear().toString(); 
	
var expDate = longMonth + " " + day  + ", " + year; 

return expDate.toString(); 

}
}

THEN

(This goes into the page code – in this case, I’m using static text fields on a dynamic page)
$w.onReady(function () {
$w(“#membersDataset”).onReady(() => {
populateCalculatedFields();
reformatJoinDate();
});
});

function populateCalculatedFields() {
const currentItem = $w(“#membersDataset”).getCurrentItem();
$w(“#expDate”).text = currentItem.expDate;
}

function reformatJoinDate() {
let originalDate = $w(“#joinDate”).text;
let date = new Date(originalDate);

const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; 

let day = date.getDate(); 
let longMonth = monthNames[date.getMonth()]; 
let year = date.getFullYear(); 
	
$w("#joinDate").text =  longMonth + " " + day  + ", " + year; 

}

A few notes…
I’m sure the function reformatJoinDate can be simplified, as this is mostly a copy of the code in data.js – but I kept getting stuck there, so this works

Also, if you are doing this in a repeater you’ll need to add a line after the onReady
$w(" #repeater1 ").forEachItem( ($w) => {

So Wayne, you’ll need to make a few changes to make this work for you:

  1. My expDate becomes your quoteDate
  2. Change the “Members” in Members_afterQuery(item) to the name of your database
  3. If your original date doesn’t come from the _createdDate, change that as well
  4. You’ll need to make changes to the page code as well to connect to your page elements

Good luck, let me know how it goes!