
Jonathan de asked a question.
I'm trying to create a date calculation that returns either an empty field or a date value depending on the field that it pulls from. Whenever I try to return null or nothing, it returns Jan 1 1970. How can I have it return a blank field?
Hi @Jonathan de, could you help us with the code you're using here so that we can check what's going wrong?
Here is the code:
var date = new Date(@dateVar)
if (date == Date(null)) {
null
} else {
date
}
If I leave null within the if statement, it says invalid date but I can save. If I just leave it empty, it doesn't let me save my change to the template.
@Jonathan de what kind of field is the calc field pulling from? Is @dateVar a date field type or another field type?
@Joel Hall Yes @dateVar is a date field type.
Thanks @Jonathan de. I think the issue with the return of Jan 1, 1970 is because of the way the calc field is handling the 'null' value. I tested this JS script below and it will read a date field and return the same date, and if the date field is empty the calc field will be empty.
@dateVar ? moment(@dateVar).format("MMMM D, YYYY") : ""
Thanks Joel, the issue is that I want the calculation field to return a date object still, not a string. The suggestion above converts it into formatted string. Is there a way to have the calculation field return the date object or nothing? According to the documentation I know it can return a date object, just unsure how to get it to return empty instead of Jan 1 1970
@Jonathan de, not sure I follow. Are you looking to copy one date field to another?
I am looking to use a calculation field to return a date value from a date field. Not in a string format, as I've noticed there've been issues with that. According to the documentation for Calculation fields, date is a valid return type. However, if the date is ever empty, I only get Jan 1 1970 instead of an empty field.
Understood @Jonathan de, curious to know what the use of the calc field returning as a date type is. However, it looks like you can return the date field as a date type in the calc by using something like this (you will need to adjust for your own timezone). If the date field is null, the calc field will return null as well.
var Date = @varDate ? moment(@varDate).tz("America/New_York").endOf("day").toDate() : null;
Date;
Thanks Joel. I think we're getting closer to the right answer. I'm getting a weird bug when using the following code modelled after the code you suggested:
var date = @Date ? moment(@Date).tz("My/Timezone").startOf("day").toDate() : null;
date
It does return null when needing to now, but otherwise only seems to return Wed 31 December 1969 5PM, no matter what date is being supplied with @Date