12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- /*
- * 日期操作
- */
- var DateOperation={
- /**
- * 日期相减 dtEnd-dtStart
- * @param {*} dtStart
- * @param {*} dtEnd
- * @param {*} datePart 返回差值部分:y-年,M-月,d-日,H-日,m-分,s-秒
- */
- subtraction:function(dtStart, dtEnd, datePart){
- var formatDtStart = new Date(Date.parse(dtStart.replace(/-/g, "/")));
- var formatDtEnd = new Date(Date.parse(dtEnd.replace(/-/g, "/")));
- if (datePart == "y")
- return parseInt((formatDtEnd-formatDtStart)/ (1000 * 60 * 60 * 24 * 365));
- if (datePart == "M")
- return parseInt((formatDtEnd-formatDtStart)/ (1000 * 60 * 60 * 24 * 30));
- if (datePart == "d")
- return parseInt((formatDtEnd-formatDtStart)/ (1000 * 60 * 60 * 24));
- if (datePart == "H")
- return parseInt((formatDtEnd-formatDtStart)/ (1000 * 60 * 60));
- if (datePart == "m")
- return parseInt((formatDtEnd-formatDtStart)/ (1000 * 60));
- if (datePart == "s")
- return parseInt((formatDtEnd-formatDtStart)/ (1000));
- return 0;
- },
- /**
- * 日期格式化,如YYYY-mm-dd HH:MM表示2019-06-06 19:45
- * @param {*} date
- * @param {*} fmt
- */
- formatDate(date,fmt) {
- let ret;
- const opt = {
- "Y+": date.getFullYear().toString(), // 年
- "m+": (date.getMonth() + 1).toString(), // 月
- "d+": date.getDate().toString(), // 日
- "H+": date.getHours().toString(), // 时
- "M+": date.getMinutes().toString(), // 分
- "S+": date.getSeconds().toString() // 秒
- // 有其他格式化字符需求可以继续添加,必须转化成字符串
- };
- for (let k in opt) {
- ret = new RegExp("(" + k + ")").exec(fmt);
- if (ret) {
- fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : DateOperation.myPadStart(opt[k], ret[1].length, "0"))
- };
- };
- return fmt;
- },
- myPadStart(str, targetLength, padString) {
- targetLength = targetLength >> 0; //floor if number or convert non-number to 0;
- padString = String(typeof padString !== 'undefined' ? padString : ' ');
- if (str.length > targetLength) {
- return String(str);
- } else {
- targetLength = targetLength - str.length;
- if (targetLength > padString.length) {
- padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
- }
- return padString.slice(0, targetLength) + String(str);
- }
- }
- }
|