JsSimpleDateFormat

  v3.0

Table of Contents

Description

JsSimpleDateFormat is for formatting Date object to be a string as the pattern we define and also for parsing a string to be a Date object based on the defined pattern. JsSimpleDateFormat works similar with Java SimpleDateFormat class which uses the same pattern letters with similar rules. If you have been familiar with Java SimpleDateFormat class, you should be able to use JsSimpleDateFormat easily. This library also contains JsDateFormatSymbols which is like Java DateFormatSymbols class to encapsulate the localizable date-time components, such as: the name of days, months etc.

Beside Java formatting pattern, this library also supports .Net DateTime formatting pattern. The .Net pattern is handled by NetDateTimeFormat class.

This library also supports the formatting for duration. The format pattern is based on .Net TimeSpan formatting pattern with some extensions. For this purpose, this library provides TimerFormat class. TimerFormatSymbols class is used to handle the localization for duration.

Date and Time Patterns

Java Compatible Date and Time Patterns

As mentioned above, JsSimpleDateFormat uses the same pattern letters with similar rules as used by Java SimpleDateFormat class. To make the same comprehension, the explanation about the pattern letters here is copied from Java Standard Ed. 8 Documentation with some modifications to note the difference between JsSimpleDateFormat and Java SimpleDateFormat.

Date and time formats are specified by date and time pattern strings. Within date and time pattern strings, unquoted letters from 'A' to 'Z' and from 'a' to 'z' are interpreted as pattern letters representing the components of a date or time string. Text can be quoted using single quotes (') to avoid interpretation. "''" represents a single quote. All other characters are not interpreted; they're simply copied into the output string during formatting or matched against the input string during parsing.

Note: There is a prominent difference between JsSimpleDateFormat and Java SimpleDateFormat class when interpreting an unrecognized letter: The list of the pattern letters:
Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
M Month in year.
Java SimpleDateFormat interprets this letter as month with context sensitive.
JsSimpleDateFormat doesn't support the context sensitive format. So, it will be exactly the same as 'L' letter.
Month 7; 07; Jul; July
L Month in year (standalone form) Month 7; 07; Jul; July
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day name in week Text Tuesday; Tue
u Day number of week (1 = Monday, ..., 7 = Sunday) Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone For formatting: GMT+07:00
For parsing, accepts format: GMT+7:00; UTC
Unlike Java, JsSimpleDateFormat doesn't support named time zone such as 'Pacific Standard Time' or 'PST'
Z Time zone RFC 822 time zone +0700
X Time zone ISO 8601 time zone +07; +0700; +07:00
Pattern letters are usually repeated, as their number determines the exact presentation:

.NET Compatible Date and Time Patterns

If you use .Net to develop the backend application, you may prefer to use .Net-compatible pattern string. For this purpose, you can use NetDateTimeFormat class. The class supports the date time pattern which is compatible with .NET Custom date and time format strings. However, there are some different behaviors. Because NetDateTimeFormat inherits JsSimpleDateFormat, it behaves more closely to its parent. For example, with pattern "HHH" and the hour is 23, .Net DateTime produces "23" but Java SimpleDateFormat produces "023". NetDateTimeFormat also produces "023", different from the real .Net version. But if you use no awkward pattern, there will be no difference (in fact, hour will not more than two digits).

The following table lists the pattern characters which applies when using NetDateTimeFormat class:
Character Explanation
d For 1 or 2 letters, it's the same as Java d letter.
For 3 or more letters, it's interpreted like Java E letter.
f One letter is the tenths of a second.
Two letters is the hundredths of a second.
Three or more letters is the milliseconds.
For example, if the value of milliseconds is 10 then the pattern "fff" will produce "010", "ff" will produce "01" and "f" will produce "0".
F The same as f letter but without the trailing zero(s). For example, if the value of milliseconds is 10 then "FFF" will produce "01", "FF" will also produce "01" and "F" will produce an empty string.
g The period or era. Like Java G letter.
h The same as Java h letter.
H The same as Java H letter.
m The same as Java m letter.
M The same as Java M letter.
s The same as Java s letter.
t The AM/PM designator. If only one letter, only the first character will be used, such as 'A' for 'AM' and 'P' for 'PM'.
y Mostly, the same as Java y letter. The difference is in the interpretation for only one letter pattern. In formatting, one letter will also produces a truncated year without century. If the truncated year is less than 10, it will produce one digit year, different from two letters that always produces two digit years. In parsing, one digit value of year is also interpreted as a abbreviated year (relative to a century).
z Timezone that uses the following formats:
one letter: "+7"
two letters: "+07"
three or more letters: "+07:00"
K It's like X letter in Java version but always uses format "+/-hh:mm"
. A decimal point. It has a special behavior when followed by the F letter pattern. If F pattern produces an empty string (because of 0 millisecond) the the decimal point isn't shown either.
' Single quote. The same as Java version, a quoted text is escaped from being interpreted as the pattern. Different from Java version, to escape a single quote, you must use backslash (\) in front of the single quoute.
" Double quote. The same as the single quote, to escape a text from interpretation. It's useful if you use many single quotes in the text.
\ Backslash. To escape a single character. The character following a backslash will not be interpreted.
/ It will be replaced by the value of DateTimeFormatInfo.DateSeparator. The default value is "/". You may change its value to another character such as "-".
: It will be replaced by the value of DateTimeFormatInfo.TimeSeparator. The default value is ":". You may change its value to another character such as ".".

Duration Patterns

Beside date-time formatting, this library also supports to format a duration. For this purpose, we use TimerFormat class. The pattern string is based on .Net Custom TimeSpan format strings but there are some differences. TimerFormat class inherits JsSimpleDateFormat class, thus the behavior of interpretation will be more closely to its parent.

Below is the list of supported pattern characters:
Character Explanation
d It's the total days of the duration without counting the remaining hours, minutes, seconds and milliseconds. The duration format doesn't support to format the number of months and years. So, the value of total days may exceed a month or a year.
h The hour part (0-23)
m The minute part (0-59)
s The second part (0-59)
f One letter is the tenths of a second.
Two letters is the hundredths of a second.
Three or more letters is the milliseconds.
For example, if the value of milliseconds is 10 then the pattern "fff" will produce "010", "ff" will produce "01" and "f" will produce "0".
F The same as f letter but without the trailing zero(s). For example, if the value of milliseconds is 10 then "FFF" will produce "01", "FF" will also produce "01" and "F" will produce an empty string.
. A decimal point. It has a special behavior when followed by the F letter pattern. If F pattern produces an empty string (because of 0 millisecond) the the decimal point isn't shown either.
- Minus sign. It will show a negative sign if the duration is negative. If positive, it will show nothing.
' Single quote. Like the date-time formatting, it's to escape a text.
\ Backslash. To escape a single character. The character following a backslash will not be interpreted.

Class JsSimpleDateFormat

Constructor

Property

Method

Class JsDateFormatSymbols

The objects of this class is to specify the name of days, months and the other keywords which are usually shown in date time information. The JsSimpleDateFormat object uses an object of JsDateFormatSymbols to get all keywords needed either for formatting or for parsing. All JsSimpleDateFormat objects always have a JsDateFormatSymbols object associated to it. When JsSimpleDateFormat object is created, it will also create JsDateFormatSymbols object based on the parameters passed to constructor. This JsDateFormatSymbols object can be obtained by getDateFormatSymbols method. You may also create a new JsDateFormatSymbols object and set it via setDateFormatSymbols method. In other words, you can set the new keywords according to your languange.

Below is an example how to change the keywords:
	var oDf = new JsSimpleDateFormat("MMM d, yyyy");
	var oSymbols = new JsDateFormatSymbols();
	oSymbols.setAmPmStrings(['AM','PM']);
	oSymbols.setEras(['AD','BC']);
	oSymbols.setMonths(['January','February','March','April','May','June','July','August','September','October','November','December']);
	oSymbols.setShortMonths(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']);
	oSymbols.setShortWeekdays(['Sun','Mon','Tue','Wed','Thu','Fri','Sat']);
	oSymbols.setWeekdays(['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']);
	oDf.setDateFormatSymbols(oSymbols);
	alert(oDf.format(new Date()));
	

Of course, you should change the words in the example above to be the appropriate words according to your language.

Another Trick
If you want set a code for your language like "en" for English and can pass this code whenever creating JsSimpleDateFormat object, do these steps. Specify the code for you language, suppose you want the code "xx". It should be two letters as specified in http://www.loc.gov/standards/iso639-2/php/English_list.php, but you may choose what you like. Nevermind if it's for your own. Create a JavaScript file and write the code like the below one inside this JavaScript file.

	JsDateFormatSymbols.__symbols__.xx = {
		amPmStrings: ['AM','PM'],
		eras: ['AD','BC'],
		months: ['January','February','March','April','May','June','July','August','September','October','November','December'],
		shortMonths: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
		shortWeekdays: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],
		weekdays: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
	};
	

Alter the words in the example above to be the appropriate words according to your language. Insert that JavaScript file in your HTML document after inserting JsSimpleDateFormat.js.

Method

Class NetDateTimeFormat

This class inherits JsSimpleDateFormat. All methods, properties and constructors are the same as its parent's. To use this class, you must insert two scripts in your HTML document:
<script src="JsSimpleDateFormat.min.js"></script>
<script src="NetDateTimeFormat.min.js"></script>

Class TimerFormat

This class inherits NetDateTimeFormat. This class is to format/parse using Duration Patterns. There is no Duration object in Javascript, hence, this class is also operated to the Date object. The duration is taken from the number of milliseconds returned by getTime method of the Date object.

This class overwrites its parent at some points as follows: To use this class, you must insert three scripts in your HTML document:
<script src="JsSimpleDateFormat.min.js"></script>
<script src="NetDateTimeFormat.min.js"></script>
<script src="TimerFormat.min.js"></script>

Class TimerFormatSymbols

This class is to localize the duration format string. It's used by TimerFormat class, especially by approxFormat method.

Constructor

The constructor requires a parameter. The parameter can be a string or an object. If it's a string then it's a locale id ('en' or 'id'). If it's an object then it defines all localized words. The structure of the object as follows:
{
  fewSeconds: 'a few seconds',
  aMinute: 'a minute',
  minutes: '${count} minutes',
  anHour: 'an hour',
  hours: '${count} hours',
  aDay: 'a day',
  days: '${count} days',
  aMonth: 'a month',
  months: '${count} months',
  aYear: 'a year',
  years: '${count} years'
}

Method

Used as Node.js Module

To install JsSimpleDateFormat package, you can use console command:
npm install jssimpledateformat
In javascript source, you can follow the example below:
import DateFormat, {JsDateFormatSymbols} from 'jssimpledateformat';

let df = new DateFormat('d MMM yyyy HH:mm:ss', new JsDateFormatSymbols('en'));
console.log(df.format(new Date()));
The other classes that can be improted are DateTimeFormatInfo, FormatError, NetDateTimeFormat, TimerFormat and TimerFormatSymbols.