Date Manipulation in SSJS

Mindwatering Incorporated

Author: Tripp W Black

Created: 10/17/2014 at 11:36 AM

 

Category:
Notes Developer Tips
XPages

Create a new NotesDateTime object:
var myDate:NotesDateTime = session.CreateDateTime("2012/01/30 00:00:01");

Get the date or time component / value only (Note this is a string returned):
var mydateonly:String = myDate.getDateOnly;
var mytimeonly:String = myDate.getTimeOnly;

Or both the date and time in the Local Time (to the server by default):
var mydatetimestr:String = myDate.getLocalTime;

To compare Dates, convert the NotesDateTime to Java DateTime:
var myJavaDate:Date = new Date(myDate.toJavaDate() );
Then use the Java DateTime functions to compare. See an example using getTime below.

Get the current document field's value as Java DateTime:
var oneDt:Date = doc1.getItemValueDate( 'MyStartDateFld');
var twoDt:Date = doc1.getItemValueDate ( 'MyEndDateFld');

You can also use the JavaScript @Date() function similar to below:
var oneDt:Date = new Date();
oneDt.setFullYear(2012, 0, 31) // Java date is 0 - 11 for month

var twoDt:Date = @Date( @Today() );
var isbeforeorsame = (@Date( oneDt ).before( twoDt ) || @Date( oneDt ).equals.( twoDt );

Format a Java date, myDate, in the local format using SSJS:
java.text.DateFormat.getDateInstance( java.text.DateFormat.SHORT, context.getLocal()).format(myDate)
(Note the keywords are SHORT, MEDIUM, LONG, and FULL.)

Format a Java time, myDate, in the local format:
java.text.DateFormat.getTimeInstance( java.text.DateFormat.SHORT, context.getLocal()).format(myDate)

Get the number of days between two java DateTimes, oneDt and twoDt:
var difference = twoDt.getTime() - oneDate.getTime();
var diffdays = (Math.floor( difference/1000/60/60/24) ) + 1;

Confirm passed date is a valid date:
(Code by Todd Morin, MW contractor)
// Checks that a date is valid (e.g., not Feb 30th, or Jan 55th, etc.).
private boolean checkDate(int date_to_check) {
// date_to_check is expected to be in modified isodate format (i.e., 20160203 for Feb 3, 2016).
final String DATE_FORMAT = "yyyyMMdd";

try {
DateFormat df = new SimpleDateFormat(DATE_FORMAT);
df.setLenient(false);
df.parse(Integer.toString(date_to_check));
return true;
} catch (Exception e) {
System.out.println("Problem with requested date: " + date_to_check);
System.exit(1);
}
return true;
}



previous page