Skip to content

Instantly share code, notes, and snippets.

@MNBuyskih
Created November 24, 2017 15:16
Show Gist options
  • Save MNBuyskih/79dc18b4ab047055f8ff2142111f6773 to your computer and use it in GitHub Desktop.
Save MNBuyskih/79dc18b4ab047055f8ff2142111f6773 to your computer and use it in GitHub Desktop.
Return formated date
/**
* parts
* YYYY - 4 digits year
* YY - 2 digits year
* M - 1-12 month
* MM - 01-12 month
* D - 1-31 day
* DD - 01-31 day
* h - 1-23 hour
* hh - 01-23 hour
* p - 1-12 am/pm hour
* pp - 01-12 am/pm hour
* a - am/pm sign
* m - 1-59 minutes
* mm - 01-59 minutes
* s - 1-59 seconds
* ss - 01-59 seconds
*
* @param {Date} date
* @param {string} input
* @returns {string}
*/
function dateFormat(date: Date, input: string): string {
const formats: { format: string, replacer: (d: Date) => string | number }[] = [
{format: "YYYY", replacer: d => d.getFullYear()},
{format: "YY", replacer: d => d.getFullYear().toString().substring(2)},
{format: "MM", replacer: d => z(d.getMonth() + 1)},
{format: "M", replacer: d => d.getMonth() + 1},
{format: "DD", replacer: d => z(d.getDate())},
{format: "D", replacer: d => d.getDate()},
{format: "hh", replacer: d => z(d.getHours())},
{format: "h", replacer: d => d.getHours()},
{
format: "pp",
replacer: d => {
const h = d.getHours();
return z(h < 13 ? h : 24 - h);
}
},
{
format: "p",
replacer: d => {
const h = d.getHours();
return h < 13 ? h : 24 - h;
}
},
{format: "a", replacer: d => d.getHours() > 12 ? "pm" : "am"},
{format: "mm", replacer: d => z(d.getMinutes())},
{format: "m", replacer: d => d.getMinutes()},
{format: "ss", replacer: d => z(d.getSeconds())},
{format: "s", replacer: d => d.getSeconds()}
];
let cursor = 0;
let output = "";
const strLen = input.length;
while (cursor < strLen) {
if (input[cursor] === "\\") {
output += input.substr(cursor + 1, 1);
cursor += 2;
continue;
}
const matched = formats
.filter(f => input.substring(cursor, cursor + f.format.length) === f.format)
.sort((a, b) => b.format.length - a.format.length)
[0];
if (matched) {
output += matched.replacer(date);
cursor += matched.format.length;
} else {
output += input[cursor];
cursor++;
}
}
return output;
}
function z(n: number): string {
return n < 10 ? `0${n}` : n.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment