I had a very challenging few minutes this morning around the Apex Datetime Method that takes two parameters; a Date and a Time. I was trying to fix a Visualforce “report” I had built that takes start and end date parameters from date fields on the Visualforce page. Well, certain records were being excluded from the reports if they happened on the last day of the date range, so I wanted to get the first second of the first day and the last second of the last day into the incoming parameters for my report date range.
I went to the Salesforce Apex Datetime Methods page, and saw that there was a newInstance method on the Datetime class that does exactly what I wanted; accepts a date and time, and yields a Datetime. So, I started with something like this:
Datetime reportStartDateTime = datetime.newInstance(reportStartDate, ’00:00:00′);
Datetime reportEndDateTime = datetime.newInstance(reportEndDate, ’23:59:59′);
I tried several different versions of the time value, but nothing was working. And, worst of all, I was getting a weird error message from Eclipse (Kepler 4.3) and/or the Force.com IDE plugin (I’m in version 31 at this point):
Compilation error: Variable does not exist: datetime
So, I started doubting if I was using a valid datetime method, and looking for missing semicolons and such. But, I finally realized that I just wasn’t supplying the time correctly. Here’s what worked:
Datetime reportStartDateTime = datetime.newInstance(reportStartDate, Time.newInstance(0,0,0,0));
Datetime reportEndDateTime = datetime.newInstance(reportEndDate, Time.newInstance(23,59,59,59));
So, the trick seems to be using the newInstance method of the Time class to get a valid time in there, rather than a string. I’m guessing there might be a string literal one CAN use to make this work, but I’m leaving that for another day, as it didn’t jump out at me in the documentation, and I’ve got code to commit on deadline…