Working with date and time in Acrobat JavaScript (Part 1 of 3)

Learn how to manipulate, display, and calculate dates and times in Acrobat JavaScript.

By Thom Parker – April 7, 2006

 

Part 1 of 3

Skill Level: Beginner to Intermediate

Material in the article applies to all Acrobat versions and variations.

Dates and times, both separately and together are useful, if not absolutely necessary, for a variety of PDF-document applications. The first, and probably the most common, use is for a date or time field on a form. Examples include the date on which the form was filled out, birthday, expiration date, start and/or end time, hours worked, days rented and so on. All of these fields require an expression of time displayed as either a date or time string.

Adobe Acrobat provides several built-in date-and-time formatting options. They are great for displaying a date/time, but what do you do if you want to use a date or time in a calculation, such as figuring out a due date or a rental cost? Or maybe you need to use the date to set various options on the form, such as changing the cost on a registration form as the event gets nearer. On a PDF form, these types of date-related operations can only be done programmatically.

So how do you work with dates and times programmatically in Acrobat?

Dates in JavaScript

First, it is important to understand that Acrobat JavaScript is divided into two parts, the core JavaScript language, which is the same for JavaScript in any application, and the Acrobat Document Object Model (DOM), which handles access to Acrobat/PDF specific functionality. Dates and times are so generally useful that they are included as part of the core JavaScript language. The Acrobat DOM helps us to use dates and times by providing some utility functions, but basic data and time manipulation is done with core JavaScript functionality so we’ll start by looking at this functionality first.

The core JavaScript language handles dates and times with a single object, the Date object. Internally this object represents a Date/Time with the number of milliseconds from some arbitrary calendar date. This object provides several functions for creating, accessing, printing, and manipulating dates and times.

In order to easily test and debug the codes several examples in this article will use the Acrobat JavaScript Console (a.k.a the console window). Activate the JavaScript Console now to test out the following code. Once the console window is open, enter the following JavaScript code:

var rightNow = new Date();

Place the cursor on the line (anywhere on the line will do as long as none of the text is selected) and press Control+Enter keys at the same time (Command+Enter for the Macintosh platform). If your keyboard has a number pad you can use the “Enter” key on the number pad without pressing the “Control”(Command on Mac) key. Excellent! You’ve just created a JavaScript Date object. Now let’s enter a line of code for displaying the Date/Time value. Enter the following code in the console window and execute it with Control+Enter:

rightNow.toString();

Your console window should look similar to Figure 1 below.

Figure 1: Using the Console Window to create and display a Date Object

Date objects are created with a special JavaScript function called a constructor. The constructor is activated with the new operator. Let’s take another look at that line of code that creates the Date object.

var rightNow = new Date();

This code uses what’s called the default constructor, which doesn’t have any input parameters. The default constructor for the Date object creates an object that represents the current date and time, so it’s what we will always use to get this information.

The Date object also includes functions for converting the raw date value into a human-readable string. We’ve already used one of these. Try a few of these other functions in the console window:

rightNow.toString();

rightNow.toLocaleString();

rightNow.toDateString();

rightNow.toLocaleDateString();

rightNow toTimeString();

rightNow.toLocaleTimeString();

rightNow.toUTCString();

rightNow.toGMTString();

They are useful for displaying the date as text, but selection of formats is limited. Acrobat JavaScript includes a much better date-formatting function. It will be discussed in Part 2 of this article.

The next step is to use the date in a calculation. The Date object can’t be used directly in a mathematical expression. Instead, we convert it into its millisecond value, and then do the calculation with this value. If necessary, the result is converted back into a Date object. The following code adds five days to the current date and then prints the new date to the console window.

// Get the current date and time 
var rightNow = new Date(); 

// Get the millisecond value 
// of the date object 
var msRightNow = rightNow.getTime(); 

// Calculate 5 days in milliseconds, 
// 5 days x 24 hrs/day x 60 min/hr x 60 sec/min x 1000 ms/sec 
var fiveDays = 5 * 24 * 60 * 60 * 1000; 

// Do Calculation var finalTime = msRightNow + fiveDays; 
// Create a new Date from the calculated value 
var theNewDate = new Date(finalTime); 

// In actual working code on a form you'll want to place the 
// result into a field value. But since this is test code we'll 
// Print the result to the Console Window (Great for Debugging) 
console.println("5 days from now is: " + theNewDate.toString());

In the example above, the ‘theNewDate’ variable is created using a different kind of date constructor than we used before. The Date object is created from the calculated millisecond value. This constructor gives us a way to create a Date object that represents any date and time. It’s useful here because we have a millisecond value as the result of a calculation, but what if we want to create a Date object from scratch using something a little more human readable than milliseconds? The Date object provides two constructors for this purpose.

var year = 2006, month = 3, day = 20; var hours = 10, minutes = 20, seconds = 0, ms = 0; var myDate = new Date(year,month,day,hours,minutes,seconds,ms); // use a date string var myDate = new Date("4/10/82");

In the first constructor, the date/time is passed as individual numbers. This is a very reliable way to create a date. The second constructor takes a date/time string as input. While using a string is convenient, date formats vary wildly and the string must exactly match one of the formats the constructor will accept, which as it turns out is not well-documented. This makes the date string constructor much less robust. In Part 2, we’ll see how Acrobat JavaScript includes some special functions that make reading formatted dates and printing dates to a string much easier.

It is often necessary to work with a span of time between two dates. The following example calculates a rental cost based on a start and end date. You can execute this code directly in the console window.

// Setup the start and end date objects 
// Nov 10th, 2005 
var startDate = new Date(2005, 11, 10); 

// Jan 5th, 2006 
var endDate = new Date(2006, 1, 5); 

// Calculate the time difference in milliseconds 
var diff = endDate.getTime() - startDate.getTime(); 

// Calculate the number of milliseconds in a day 
// 1 day x 24 hrs/day x 60 min/hr x 60 sec/min x 1000 ms/sec 
var oneDay = 24 * 60 * 60 * 1000; var price = 3.00; // $3.00/day; 

// Calculate the number of days from start to end 
// and the total cost 
var numOfDays = diff/oneDay; 
var totalCost = numOfDays * price; 

// Build a message for the user and print it to the console 
var strMessage = "# of days = " + numOfDays; strMessage += " : price/day= " + price; strMessage += " : total cost = " + totalCost; console.println(strMessage);

Now that we know how to create, print and use JavaScript dates in calculations, we’re ready to gainfully apply this knowledge to improving a PDF. Part 2 will show how dates can be displayed and read from form fields and be used in form calculations, and will introduce improved date functions specific to Acrobat.

>> Go to Part 2



Related topics:

JavaScript

Top Searches:


0 comments

Comments for this tutorial are now closed.

Comments for this tutorial are now closed.