JsSimpleDateFormat
JsDateFormatSymbols
NetDateTimeFormat
TimerFormat
TimerFormatSymbols
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.DateTime
formatting pattern. The .Net pattern is handled by
NetDateTimeFormat
class.TimeSpan
formatting pattern with some extensions. For this purpose,
this library provides TimerFormat
class.
TimerFormatSymbols
class is used
to handle the localization for duration.
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
.
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.
JsSimpleDateFormat
and Java SimpleDateFormat
class when
interpreting an unrecognized letter:
a
' to 'z
' or 'A
'
to 'Z
') in the pattern which doesn't have a representation (not listed
in the list below), such as B
, Java SimpleDateFormat
class will raise error. JsSimpleDateFormat
, however, will not
interpret that letter but will show that letter as is.
Pattern letters are usually repeated, as their number determines the exact presentation:
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.
JavaSimpleDateFormat
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
JsSimpleDateFormat
only supports Gregorian calendar):
JsSimpleDateFormat
must interpret the abbreviated year relative to
some century. The begin of century is set by
set2DigitYearStart
method.
By default, it's 80 years before the JsSimpleDateFormat
instance is
created. For example, using a pattern of "MM/dd/yy" and the begin of century is
1917, the string "01/11/12" would be interpreted as Jan 11, 2012 while the string
"05/04/64" would be interpreted as May 4, 1964. During parsing, only strings
consisting of exactly two digits, will be parsed into the default century. Any
other numeric string, such as a one digit string, a three or more digit string,
is interpreted literally.SimpleDateFormat
still explains how the negative year is interpreted. Actually, the recent version
of SimpleDateFormat
will raise an exception when parsing a negative
year. Therefore, in the current version, JsSimpleDateFormat
doesn't
support a negative year. Please use the era designator (BC) instead.GMTOffsetTimeZone:Hours must be between 0 and 23, and Minutes must be between 00 and 59.GMT
Sign Hours:
Minutes Sign: one of+ -
Hours: Digit Digit Digit Minutes: Digit Digit Digit: one of0 1 2 3 4 5 6 7 8 9
RFC822TimeZone: Sign TwoDigitHours Minutes TwoDigitHours: Digit DigitTwoDigitHours must be between 00 and 23. Other definitions are as for general time zones.
ISO8601TimeZone:
OneLetterISO8601TimeZone
TwoLetterISO8601TimeZone
ThreeLetterISO8601TimeZone
OneLetterISO8601TimeZone:
Sign TwoDigitHours
Z
TwoLetterISO8601TimeZone:
Sign TwoDigitHours Minutes
Z
ThreeLetterISO8601TimeZone:
Sign TwoDigitHours :
Minutes
Z
Other definitions are as for general time zones
or RFC 822 time zones.
"Z"
is produced. If
the number of pattern letters is 1, any fraction of an hour is ignored. For example,
if the pattern is "X"
and the time zone is "GMT+05:30"
,
"+05"
is produced.
"Z"
is parsed as the UTC time zone designator.
General time zones are not accepted.
FormatError
is thrown.
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).
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 JavaE
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. IfF
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"."
.
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.
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. IfF
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.
JsSimpleDateFormat
JsSimpleDateFormat()
JsSimpleDateFormat
object using default pattern and
default locale. Default pattern is JsSimpleDateFormat
and then overwrite
_getDefaultPattern
method, like the below one. Suppose the
default pattern you want is function MyJsSimpleDateFormat() { JsSimpleDateFormat.apply(this,arguments); } MyJsSimpleDateFormat.__extends__(JsSimpleDateFormat, { _getDefaultPattern: function() { return "MMM dd, yyyy HH:mm a"; } });
__extends__
method is written in JsSimpleDateFormat.js.
If using usual way, we write like this:
function MyJsSimpleDateFormat() { JsSimpleDateFormat.apply(this,arguments); } MyJsSimpleDateFormat.prototype = new JsSimpleDateFormat(); MyJsSimpleDateFormat.prototype._getDefaultPattern = function() { return "MMM dd, yyyy HH:mm a"; }
or you may use ES6 syntax which is more simple:
class MyJsSimpleDateFormat extends JsSimpleDateFormat { _getDefaultPattern() { return "MMM dd, yyyy HH:mm a"; } }
JsSimpleDateFormat(sPattern)
JsSimpleDateFormat
object using the pattern
as written in parameter and using default locale
that is English.sPattern
is the pattern for formatting date time
that will be used by this object.
JsSimpleDateFormat(sPattern, sLocale)
JsSimpleDateFormat
object using the pattern
and the locale as defined by parameter.sPattern
is the pattern for formatting date time
that will be used by this object.
sLocale
is the locale code which defines the
language that will be used. There are two codes provided by
this library, those are en
(English) and
id
(Indonesian). But you can define the new
one. For further information, see
JsDateFormatSymbols
.
JsSimpleDateFormat(sPattern, oSymbols)
JsSimpleDateFormat
object using the pattern
and the locale as defined by parameter.sPattern
is the pattern for formatting date time
that will be used by this object.
oSymbols
is a
JsDateFormatSymbols
object which defines the name of days, months etc, which are usually shown
in date time information.
flexWhiteSpace
true
(by default) then the users can type any
number of spaces regardless the number of spaces defined in the pattern
for that position. This flexibility makes easier for the users so that
they don't need to remember how many spaces they have typed. This setting
also ignores the kind of white space (space, tab or new line). If the
value of this property is false
, it will parse strictly, the
number and the kind of white space. This property must be set before
invoking parse
method.
isLenient
JsSimpleDateFormat
does strict parsing. It will
check the consistency among date time components. For example, with
pattern "EEE, MMM d, yyyy", it will fail to parse "Mon, Feb 1, 2008"
because in the fact, "Feb 1, 2008" is Friday. If isLenient
is set to true
, JsSimpleDateFormat
will parse
more loosely. In the previous case, it will parse the string
successfully.
applyPattern(sPattern)
sPattern
is the new pattern will be applied.
format(oDate)
Date
object using the pattern applied to this object.oDate
is the Date
object will be formatted.
get2DigitYearStart()
Date
object that have been set by
set2DigitYearStart
method. If set2DigitYearStart
method has not been invoked yet, it will return the Date
object representing
the date time 80 years before this JsSimpleDateFormat
object
is created.Date
object which its year is the begin of century.
getDateFormatSymbols()
JsDateFormatSymbols
object used by this object.
See setDateFormatSymbols
JsDateFormatSymbols
object used by this object.
parse(s)
Date
object based on the pattern used by
this object. It's possible there will be a missing field in the pattern
to construct a complete date time. Perhaps, there is no year or month or
day etc. To avoid that, in the beginning of parsing, this method will
get the initial date time and then parse and set the appropriate field as
found in the string. The initial date time is "January 1, 1970 00:00:00.000"
based on your local time. If you want change the initial date time, you may
create your own class inherited from JsSimpleDateFormat
and overwrite _getInitDate
method as below (suppose you want
the iniatial date time is the current date time):function MyJsSimpleDateFormat() { JsSimpleDateFormat.apply(this,arguments); } MyJsSimpleDateFormat.__extends__(JsSimpleDateFormat, { _getInitDate: function() { return new Date(); } });
__extends__
method is written in JsSimpleDateFormat.js.
If using usual way, we write like this:
function MyJsSimpleDateFormat() { JsSimpleDateFormat.apply(this,arguments); } MyJsSimpleDateFormat.prototype = new JsSimpleDateFormat(); MyJsSimpleDateFormat.prototype._getInitDate = function() { return new Date(); }
or you may use ES6 syntax which is more simple:
class MyJsSimpleDateFormat extends JsSimpleDateFormat { constructor(sPattern, param) { super(sPattern, param); this.set2DigitYearStart(new Date(2000, 0 , 1)); } _getInitDate() { return new Date(); } }
parse
method will return null
if the string
cannot be parsed to be a valid date time. Note, the method may not use
the entire text, only a substring positioned at index 0. For example,
"Jan 3, 2008 is Thursday" will be parsed successfully using pattern
"MMM d, yyyy" even if the remaining string " is Thursday" doesn't match
the pattern.
s
is a string to be parsed.
Date
object as the result of parsing or null
if
the parsing failed.
parse(s, oPos)
oPos
.
If the parsing is successful, this index will be updated to the index after the last
character parsed successfully (this method may not parse until the end of string)
and the Date
object which is the result of parsing is returned. The
updated index is useful to determine the starting index for the next parsing.
Paramerter oPos
is an object whose properties: index
and errorIndex
. The index
property is the starting
index as explained before. The errorIndex
property will be used
if the parsing failed. It notes the index where the error begins to happen.
If an error occurs, the index
property will not be updated but the
errorIndex
property will be updated. Example:
var oDf = new JsSimpleDateFormat("MMM d, yyyy"); var s = "The date of Jan 3, 2008 is Thursday"; var oPos = {index: 12, errorIndex: -1}; var oDate = oDf.parse(s, oPos);
After parsing, index
property will be updated become 23.
As example above, initiate the value of errorIndex
property
to -1 because if an error occurs, it will be updated to the non negative
value. Negative value will differentiate from the index where the error occurs.
So if errorIndex
property becomes 0 or higher after parsing then
an error occurs. Another clue, this method will return null
if the string cannot be parsed to be a valid date time.
If you don't need the return back about index but only want to determine the
starting index, you may do it like this:
var oDate = oDf.parse(s, {index:3});
For further information, see another parse
method.
s
is a string to be parsed.
oPos
is an object whose index and error index information as
explained above.
Date
object as the result of parsing or null
if
parsing is failed.
set2DigitYearStart(oStartDate)
Date
object. What you must do is to create a Date
object and set
its year by invoking setFullYear
method. Then pass this
Date
object as parameter.oStartDate
is a Date
object which its year is
the begin of century.
setDateFormatSymbols(oFormatSymbols)
JsDateFormatSymbols
object that will be used by this object. JsDateFormatSymbols
object
determines the name of days, months etc, which are usually shown in date time
information. You can create your own
JsDateFormatSymbols
object and set your own name of days and months. Pass that
JsDateFormatSymbols
object as the parameter of this method.
When a JsSimpleDateFormat
object is created, it will
create a JsDateFormatSymbols
object for it, based on
the parameter of constructor.oFormatSymbols
is a JsDateFormatSymbols
object to be set.
toPattern()
JsDateFormatSymbols
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.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.
getAmPmStrings()
getEras()
getMonths()
getShortMonths()
getShortWeekdays()
getWeekdays()
setAmPmStrings(arAmPmStrings)
arAmPmStrings
is an array of "AM" and "PM" text. "AM" is the first elements.
setEras(arEras)
arEras
is an array of era designators. The first element is the designator
which is the same as "AD".
setMonths(arMonths)
arMonths
is an array of the month names, the first until the twelfth month.
setShortMonths(arShortMonths)
arShortMonths
is an array of the abbreviated month names, the first until the twelfth month.
The abbreviated month name usually consists of three letters.
setShortWeekdays(arShortWeekdays)
arShortWeekdays
is an array of the abbreviated day names.
Sunday is the first element. The abbreviated day name usually consists of three letters.
setWeekdays(arWeekdays)
arWeekdays
an array of the day names. Sunday is the first element.
NetDateTimeFormat
<script src="JsSimpleDateFormat.min.js"></script> <script src="NetDateTimeFormat.min.js"></script>
TimerFormat
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.TimerFormatSymbols
object, not JsDateFormatSymbols
approxFormat(oDate, sPrefix, sSuffix)
from*
and to*
method of moment
package.Date
object or an integer. If it's an
integer then it's the total number of milliseconds for the duration.format
Date
object or an integer. If it's an integer
then it's the total number of milliseconds for the duration.
getDateFormatSymbols
getTimerFormatSymbols
method.
getTimerFormatSymbols
TimerFormatSymbols
object that is being used.
setDateFormatSymbols
setTimerFormatSymbols
method.
setTimerFormatSymbols
TimerFormatSymbols
object.
<script src="JsSimpleDateFormat.min.js"></script> <script src="NetDateTimeFormat.min.js"></script> <script src="TimerFormat.min.js"></script>
TimerFormatSymbols
TimerFormat
class, especially by
approxFormat
method.
{ 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' }
getFewSeconds
and setFewSeconds(s)
getAMinute
and setAMinute(s)
getMinutes
and setMinutes(s)
getAnHour
and setAnHour(s)
getHours
and setHours(s)
getADay
and setADay(s)
getDays
and setDays(s)
getAMonth
and setAMonth(s)
getMonths
and setMonths(s)
getAYear
and setAYear(s)
getYears
and setYears(s)
npm install jssimpledateformatIn 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
.