扫码关注官方订阅号
我想写一个组件,在输入数字中比如:201705 自动格式化日期格式,最终日期格式为:2017-05 再次输入06自动格式化2017-05-06
小伙看你根骨奇佳,潜力无限,来学PHP伐。
Edit: 对提出的 case 做简单转换:
const date str = '20170523' const result = new Date() result.setFullYear(parseInt(str.substr(0, 4))) result.setMonth(parseInt(str.substr(4, 2)) - 1) result.setDate(parseInt(str.substr(6, 2))) // 函数定义见下 getDateFromTimestamp(result.getTime())
一个简单的实现如下:
// 1495517932472 毫秒级时间戳 const date = new Date().getTime() function formatMonth (num) { return [ '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12' ][num] } function getDateFromTimestamp (ts) { const date = new Date(ts) const YYYY = date.getFullYear() const MM = formatMonth(date.getMonth()) const DD = date.getDate() return `${YYYY}-${MM}-${DD}` } // 2017-05-23 console.log(getDateFromTimestamp(date))
You maybe need momentjs
funtion format_num_to_date(num) { var str = String(num); if (str.length === 8) { var date = str.substr(0,4) + '-' + str.substr(4,2) + '-' + str.substr(6); return date; } } format_num_to_date(20170523);
//时间格式化 // var time1 = new Date().Format(“yyyy-MM-dd”); // var time2 = new Date().Format(“yyyy-MM-dd HH:mm:ss”); Date.prototype.Format = function (fmt) { //author: meizz var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": this.getHours(), //小时 "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 "S": this.getMilliseconds() //毫秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; }
let yyyymmdd = (date, sep = '-') => { return [ date.getFullYear(), date.getMonth()+1, date.getDate() ].map(d => d.toString()) .map(d => ('00' + d).slice(d.length >= 4 ? -4 : -2)).join(sep); }
原生<input type="date" pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}">不好吗?
<input type="date" pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}">
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
扫描下载App
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
Edit: 对提出的 case 做简单转换:
一个简单的实现如下:
You maybe need momentjs
原生
<input type="date" pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}">
不好吗?