diff --git a/examles/sampleCommon.js b/examles/sampleCommon.js new file mode 100644 index 0000000..98cc6be --- /dev/null +++ b/examles/sampleCommon.js @@ -0,0 +1,4 @@ +const common = require('../src/lib/common.js'); + +console.log(common.formatDatetime(new Date(), 'yyyy/MM/dd hh:mm:ss')); +console.log(common.formatDatetime(new Date(), 'yyyy-MM-ddThh:mm:ss')); \ No newline at end of file diff --git a/src/lib/common.js b/src/lib/common.js index e69de29..bf1fc36 100644 --- a/src/lib/common.js +++ b/src/lib/common.js @@ -0,0 +1,22 @@ +const common = { + /** + * 日時データを指定フォーマットで文字列化する + * @param {Date} dt + * @param {String} fmt + * @returns {String} + */ + formatDatetime(dt,fmt="yyyy-MM-dd hh:mm:ss"){ + const pad = (n) => n < 10 ? '0' + n : n; + const replacements = { + "yyyy": dt.getFullYear(), + "MM": pad(dt.getMonth() + 1), + "dd": pad(dt.getDate()), + "hh": pad(dt.getHours()), + "mm": pad(dt.getMinutes()), + "ss": pad(dt.getSeconds()) + }; + return fmt.replace(/yyyy|MM|dd|hh|mm|ss/g, (match) => replacements[match]); + } +} + +module.exports = common; \ No newline at end of file diff --git a/tests/test_common.js b/tests/test_common.js new file mode 100644 index 0000000..e69de29