0

I am working with Adobe Acrobat XI Pro. I am using three text boxes for the date with the code below:

var month = this.getField("DATE_MONTH").valueAsString;
var day = this.getField("DATE_DAY").valueAsString;
var year = this.getField("DATE_YEAR").valueAsString;
var date = month + "/" + day + "/" + year;
var test_date = new Date();
test_date.setDate(test_date.getDate());

if(date != test_date){
    app.alert("The entered value needs to be TODAY'S date in the format mm/dd/yyyy");
}

Originally, this code was working-- only throwing an error if the date chosen was not today's date. Now I get an error no matter what date is chosen.

1 Answers1

0

Variable date is a string in the format m/d/y, but test_date is a Date object. The != comparison will force the Date to be converted to a string, now the comparison is effectively:

date != test_date.toString();

Since the next version of ECMA-262 requires Date.prototype.toString to return a string in RFC 2822 format (e.g. Mon, 25 Dec 1995 13:30:00 GMT), most new browsers are implementing the format now. The RFC format does not match a string in the format m/d/y so the comparison will always evaluate to true,

E.g.

'12/25/1995' != 'Mon, 25 Dec 1995 13:30:00 GMT'

will always be true for any date when using those formats. For an answer, see Compare two dates with JavaScript.

Just to help out, I don't know anything about ECMAScript in PDFs, but you may be able to do:

var month = this.getField("DATE_MONTH").valueAsString;
var day = this.getField("DATE_DAY").valueAsString;
var year = this.getField("DATE_YEAR").valueAsString;

// Compare date time values with time set to 00:00:00
if (+new Date(year, month - 1, day) != new Date().setHours(0,0,0,0))

The unary + will convert the Date to a number, and the return value from setHours is the new time value (also a number) so both values will be coerced to number. If you want something more explicit, consider:

if (new Date(year, month - 1, day).getTime() != new Date().setHours(0,0,0,0))

var d = new Date();
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();

// Is today != today?
console.log( +new Date(year, month - 1, day) != new Date().setHours(0,0,0,0));

// Is today != tomorrow?
console.log( new Date(year, month - 1, day + 1).getTime() != new Date().setHours(0,0,0,0));

PS

This: test_date.setDate(test_date.getDate()) does nothing useful. It just sets test_date's date to the same value that it already has. ;-)

RobG
  • 142,382
  • 31
  • 172
  • 209
  • I have changed date != test_date to date != test_date.toString() but that does not seem to solve the issue. Any other suggestions? – Ashton Binkley Aug 06 '18 at 17:07
  • @AshtonBinkley—the very first part of my answer explains why, the rest of the answer explains what you might try instead (the bit after "*…you may be able to do…*". :-) – RobG Aug 07 '18 at 02:46