Search code examples
xpagesdate-comparisonssjs

Compare two date fields using SSJS


I have two date fields in a document. I need to check if these two fields contain the same value using SSJS.

The values in those fields can either be a datetime or "not set" (empty)

how can I do that?

Thomas


Solution

  • The easiest way is to compare the String values of the dates:

    var d1 = document1.getItemValue("date1").toString();
    var d2 = document1.getItemValue("date2").toString();
    return d1 == d2
    

    When you want to compare only dates, you can do this by converting the date using SimpleDateFormat java class.

    var sdf = new java.text.SimpleDateFormat("YYYY-MM-dd");
    var d1 = document1.getItemValueDate("date1");
    var d2 = document1.getItemValueDate("date2");
    d1 = d1 == null?"":sdf.format(d1);
    d2 = d2 == null?"":sdf.format(d2);
    return d1.equals(d2)
    

    You can adjust the formatting in the first line to comply to your needs. More info on formatting can be found here