y: date.getFullYear(), 如果报错 time 要new Data(time)
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <!-- vue --> <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> <!-- element引入样式 --> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> <!-- element引入组件库 --> <script src="https://unpkg.com/element-ui/lib/index.js"></script> <!--Axios--> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <div id="App"> <div class="block"> <span class="demonstration">默认</span> <el-date-picker v-model="value1" type="datetime" placeholder="选择日期时间" @change="changeDate"> </el-date-picker> </div> <span>{{d}}<span/> <br/> <span>{{d | parseTime}}<span/> </div> </body> <style scoped> </style> <script> Vue.filter("parseTime", function(time, cFormat) { //全局方法 Vue.filter() 注册一个自定义过滤器,必须放在Vue实例化前面 if (arguments.length === 0) { return null } const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}' let date if (typeof time === 'object') { date = time } else { if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) { time = parseInt(time) } if ((typeof time === 'number') && (time.toString().length === 10)) { time = time * 1000 } date = new Date(time) } const formatObj = { y: date.getFullYear(), m: date.getMonth() + 1, d: date.getDate(), h: date.getHours(), i: date.getMinutes(), s: date.getSeconds(), a: date.getDay() } const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => { const value = formatObj[key] // Note: getDay() returns 0 on Sunday if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] } return value.toString().padStart(2, '0') }) return time_str }); var vm = new Vue({ el: "#App", data: { value1: '', d: '2021-12-16T23:36:21' }, created() { }, methods: { parseTime(time, cFormat) { if (arguments.length === 0) { return null } const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}' let date if (typeof time === 'object') { date = time } else { if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) { time = parseInt(time) } if ((typeof time === 'number') && (time.toString().length === 10)) { time = time * 1000 } date = new Date(time) } const formatObj = { y: date.getFullYear(), m: date.getMonth() + 1, d: date.getDate(), h: date.getHours(), i: date.getMinutes(), s: date.getSeconds(), a: date.getDay() } const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => { const value = formatObj[key] // Note: getDay() returns 0 on Sunday if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] } return value.toString().padStart(2, '0') }) return time_str }, // js 日期选择 changeDate(value) { console.log(value) var mydata = this.parseTime(value) console.log(mydata ) } } }) </script> </html>