|Simple Date Formatting in SSJS
When it comes to Date and Times in any programing language there is always a little bit of ‘hair pulling out’ when you realize that there are a multitude of ways to store and manipulate the DateTime object and that how you did it in one language is not always the same as how it is done in another language.
With SSJS in XPages it doesn’t get any less confusing. You may have dates that are stored in the NotesDateTime format but you can also have dates that are in the JavaDate format which are completely different, but thankfully converting between the two has been made nice and easy. if you have a NotesDateTime then you can use the .toJavaDate() method to return a date in the JavaDate format. If you have a JavaDate then you can use session.createDateTime(JavaDate) to create a new NotesDateTime object from the existing JavaDate object.
When it comes to building a string out of the date in a particular format, for example for the filename of a report, you could write a load of code that uses the .getMonth(), .getYear() and .getDate() methods, adds 1 to the methods that return zero based ints and then convert them to strings and concatenate them to build your specially formatted string OR you could just make use of the SimpleDateFormatter class that is available in Java and have that do all the hard work for you…
First we need to import the Java package that contains the SimpleDateFormatter so that SSJS knows about it so add the following at the top of your script
then we need to get our JavaDate object. Lets assume that we have a Notes document with a field called ReportDate on it with the date in there…
var reportDateNotes:NotesDateTime = document.getFirstItem(“ReportDate”);
var reportDateJava:Date = reportDateNotes.toJavaDate();
Now that we have our JavaDate object we need to create a SimpleDateFormat object and pass in the format that we need in the constructor
var dateFormatter:SimpleDateFormat = new SimpleDateFormat(“yyyyMMdd-hhmma”);
and finally to get the JavaDate formatted using the format that we have specified we just call the .format() method and pass in the JavaDate that we need formatted.
For the SimpleDateFormat constructor you can pass in any of the codes details in it’s javaDoc which is available here to format the date any way that you want.
Aug 20, 2012
Sorry, no records were found!
| Recent Blog Posts