How to ask if a date value is empty
Hi, I have two date fieds in an app: date1 and date2. Every entry has date1 filled but only some have date2.
I want to calculate the number of dates between today and date2, however, if date2 is empty, the calculation should be the days between today and date1.
I havent been able to find how to use javascript or moment() in an if () calculation where I can ask if date2 is empty.
Thanks a lot for your help,
-
Hi,
this code should do what you want:
var date1 = @date1fFeld; var date2 = @date2Field; var today = moment(); var diff1 = date1.diff(today, 'days'); var diff2 = date2.diif(today, 'days'); date2 != null ? diff2 : diff1
(read as: IF date2 not empty than calculate diff2, else diff1)
But be careful: "today" is a static value, it's only been updated if one of the variables in the calculation field changes.
Example: You enter the date 2 value today (Tuesday, 24.02. )Then you have the values day2 = 28.02.2015 and today = 24.02.2015 = result: diff2 = 4 days: But this result "4 days" will also been shown tomorrow (25.02.).Rainer
-
Hi Hamid & Julian,
yes, you can do it that way. But there is an important difference:
.fromNow() delivers the result as a text string, .diff delivers a number. If you need the result for further calcutions, it's better to have a number.Another difference: With .diff you define more confortable in which unit the result should be shown, If you use .fromNow it sets the unit automatically (or you have to write some more code).
I'm sorry, but in my above code there are typos und mistakes (did it to fast). Here's the correct code:
var date1 = moment(@date1Field) ; var date2 = moment(@date1Field); var today = moment(); var diff1 = date1.diff(today, 'd','h'); //using 'd','h' delivers a result like 1,25 days, only 'd' results in 1 var diff2 = date2.diff(today, 'd','h'); date2 != null ? diff2 : diff1
(instead of != null one can use .isValid() as well)
Rainer -
Reiner thanks a lot for your help, I really appreciate it. Following what I learned from your post, I decided to create a calculated field where I would have the latest date. The app is for event management and it has two dates: session1 and session2. Each event has either one session or two, so, in some cases date2 will be empty. I tryed to calculate the latest date in each event:
var date1 = moment(@session1).format("DD MMM");
var date2 = moment(@session2).format("DD MMM");date2!= null ? date2 : date1
date2With this code, I get the correct result if there is a session2 but I get "Invalid date" if there is no date2.
What am I doing wrong?
Thanks a lot
Please sign in to leave a comment.
Comments
8 comments