JS 中 Date() 的其他操作集锦
好吧,这周完全是个业务型的程序猿了,明显地能感觉到洗头发时头皮都会有点疼,是秃顶的前兆。
算得上收获的就是有较多的接触到计算时间方面的事件...嗯,几个笔记分享一下
1 2 3 4 | // 处理 /Date("xxxxxxxxx")/ 形态的时间戳 function changeDate(datetime) { return new Date(parseInt(datetime.replace( "/Date(" , "" ).replace( ")/" , "" ), 10)); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // 将时间字符串转换成 Date 形式 // 这里插播一个 bug,苹果机不能玩 new Date("xxxx-xx") 这样的字符串形式,所以得改成 new Date("xxxx","xx") // 只能固定为年月日时分秒这样的格式,智能不了呀 function initDate(date) { if (arguments.length > 1) var D = arguments; else if ( typeof date == "string" ) var D = date.split(/[- \.:\/]/); else return new Date(date); switch (D.length) { case 1: return new Date(D); break ; case 2: return new Date(D[0], --D[1]); break ; case 3: return new Date(D[0], --D[1], D[2]); break ; case 4: return new Date(D[0], --D[1], D[2], D[3]); break ; case 5: return new Date(D[0], --D[1], D[2], D[3], D[4]); break ; case 6: return new Date(D[0], --D[1], D[2], D[3], D[4], D[5]); break ; } } |
1 2 3 4 5 | // 计算变化多少天后的日期 function DateAddDay(date, days) { var d = new Date(date); return new Date(d.setDate(d.getDate() + days)); } |
1 2 3 4 5 | // 该月第一天的日期 function FirstDay(date) { var d = new Date(date); return new Date(d.setDate(1)); } |
1 2 3 4 5 6 7 8 | // 计算该年该月有几天 function HowMuchDay(month, year) { if (!year) year = new Date().getFullYear(); var y = [31, (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; for ( var i in y) { if (i == (month - 1)) return y[i]; } } |
1 2 3 4 5 6 7 | // 倒计时,需要秒数则可以给返回值加上 .getTime() // 时间是可以做减法的哟,我才知道 function TimeCountDown(endTime) { var now = new Date(); var target = initDate(endTime); // initDate 前面有提 return new Date(target - now); } |
1 2 3 4 5 | // 获得本周周一的日期,其他都可以根据 DateAddDay 来算咯 function FirstDayInThisWeek(date) { var date = initDate(date); return DateAddDay(date, 1 - date.getDay()); } |
1 2 3 4 5 | // 转换这天星期几 function ConvertDay(date) { var arr = [ "一" , "二" , "三" , "四" , "五" , "六" , "日" ] return arr[initDate(date).getDay()-1]; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // 将 Date 转换成字符串格式 // pattern 的格式嘛,只要有着几个字母就行了 // yyyy = 年 mm = 月 dd = 日 hh = 小时 nn = 分 ss = 秒 w = 星期几 function ConvertDateToString(date, pattern) { var str = pattern; str = str.replace(/y{4}/i, date.getFullYear()); str = str.replace(/m{2}/i, (date.getMonth()+1)); str = str.replace(/d{2}/i, date.getDate()); str = str.replace(/h{2}/i, date.getHours()); str = str.replace(/n{2}/i, date.getMinutes()); str = str.replace(/s{2}/i, date.getSeconds()); str = str.replace(/w/i, "星期" +ConvertDay(date)); return str; } |
1 2 3 4 5 6 7 8 9 | // 自动补零 function addZero(num, n) { var len = num.toString().length || 2; while (len < n) { num = "0" + num; len++; } return num; } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步