I wrote some code to add a “Date Joined” field to my database. I formatted the field to be date and time. It looks like the below. When the data gets imported upon a user signing up it says that the cell value is text and to change it to a date, but the field is already set to a date. Any way to change the format so when I go to import the Joined Now data it is properly formatted?
This is my before hook code:
export function Users_beforeInsert(item, context) {
let hookContext = context;
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd = ‘0’+dd;
}
if(mm<10) {
mm = ‘0’+mm;
}
today = mm + ‘/’ + dd + ‘/’ + yyyy + " 00:00";
This line:
today = mm + ‘/’ + dd + ‘/’ + yyyy + " 00:00";
returns a string because of the slashes you put in. You should return a date like this:
datNewDate = new Date( year, month, day, hours, minutes, seconds, milliseconds ) ;
and return that, without any formatting (like slashes). Formatting is done after reading and then displaying, not when writing a date. A date in JS is a number, a whole bunch a millisecs from 1 jan 1970, if I remember correctly.
Same case of Manual upload in JSON form and its uploading. Dates are getting uploaded as string and not as Javascript date object. From this thread I used the Hooks
In Hooks before Insert, I am using this script but its not getting converted. Please help
export function LM_Attendance_beforeInsert(item, context) {
let hookContext = context;
var at_date_hk = item.at_date;
var datNewDate = new Date(at_date_hk) ;
The problem is that you’re inserting text into a date field (even if it’s text that looks remarkably like a date). Don’t create a string using the Javascript date object; pass into the database the date object itself.
Have tried a few work arounds for this - nothing seems to work. Any more detailed help would be very much appreciated! This is very frustrating.
I tried creating new objects from JSON and converting date properties to Date type before import. No luck
I then tried creating the object, inserting and then retrieving and then converting the object.date value to Date and directly updating this. No luck again… It ends up still with an unusable literal somewhere when calling update().
Ok after some more digging realised that it was that Date object needed to be declared...
var x = new Date(results.date);
results.date = x;
wixData.update(collection, results)