java.text.simple-date-format
v1.0.0
Published
A utility class to format Date object in Javascript. It is heavily influenced by SimpleDateFormat class of Java and follow most of its specifications.
Readme
Date format like java SimpleDateFormat
var dateFormat = new SimpleDateFormat('yyyy-MM-dd HH:mm:ss');
var date1 = new Date(2000,1,1,1,1,1,999);
assert.strictEqual(dateFormat.format(date1),"2000-02-01 01:01:01");var dateFormat = new SimpleDateFormat('yyyy-MM-dd HH:mm:ss');
var date1 = new Date(2000,1,1,1,1,1);
assert.strictEqual(dateFormat.parse("2000-02-01 01:01:01").getTime(),date1.getTime());Supported pattern letters
| Letter | Meaning | Example | |--------|--------------------|-----------------| | y | Year | yy → 25, yyyy → 2025 | | M | Month | M → 6, MM → 06 | | d | Day in month | d → 1, dd → 01 | | H | Hour (0-23) | H → 9, HH → 09 | | h | Hour (1-12) | h → 9, hh → 09 | | m | Minute | m → 5, mm → 05 | | s | Second | s → 3, ss → 03 | | S | Millisecond | S → 9, SSS → 009 | | a | AM/PM marker | AM, PM |
Quoting and escaping
Like Java's SimpleDateFormat, single quotes can be used to quote literal text:
var dateFormat = new SimpleDateFormat("'Date:' yyyy-MM-dd");
dateFormat.format(new Date(2025, 5, 16)); // "Date: 2025-06-16"Two consecutive single quotes produce a literal single quote:
var dateFormat = new SimpleDateFormat("hh''mm");
dateFormat.format(new Date(2000, 0, 1, 9, 5)); // "09'05"Inside quoted text, use '' to escape a single quote:
var dateFormat = new SimpleDateFormat("'it''s' yyyy");
dateFormat.format(new Date(2025, 0, 1)); // "it's 2025"CJK characters as literals:
var dateFormat = new SimpleDateFormat("yyyy'年'MM'月'dd'日'");
dateFormat.format(new Date(2025, 5, 16)); // "2025年06月16日"12-hour time with AM/PM
var dateFormat = new SimpleDateFormat('hh:mm a');
dateFormat.format(new Date(2000, 0, 1, 0, 0)); // "12:00 AM" (midnight)
dateFormat.format(new Date(2000, 0, 1, 12, 0)); // "12:00 PM" (noon)
dateFormat.format(new Date(2000, 0, 1, 13, 5)); // "01:05 PM"Not supported
Y(week year) - a common pitfall in Java, intentionally not implementedD(day in year) - a common pitfall in Java, intentionally not implementedE(day name),G(era),w/W(week),F,k,K,z,Z,X(timezone)
