设置字符串到Vuejs的日期格式



我从API获取一个格式如下的日期字符串:DD_MM_YYYY_hh_MM_ss

我想以以下格式显示字符串:DD/MM/YYYY hh:MM:ss

我怎样才能做到这一点?

您可以根据下划线序列在输入字符串中的位置将其替换为适当的字符:

function convertDate(date) {
return date.replace(/_+/g, (_, n) => (n < 10) ? "/" : (n > 10) ? ":" : " ");
}
console.log(convertDate("DD_MM_YYYY_hh_mm__ss"));

或者稍微简单一点:

function convertDate(date) {
let n = 0; return date.replace(/_+/g, () => "// ::"[n++]);
}
console.log(convertDate("DD_MM_YYYY_hh_mm__ss"));

单向:

const str = '18_03_2022_12_21_34'
// to string
const res = str.split('_')
const r = res.slice(0, 3).join('/') + ' ' + res.slice(-3).join(':')
console.log(r)
// or to date
console.log(new Date(res.slice(0, 3).join('/').split('/').reverse().join('/') + ' ' + res.slice(-3).join(':')))

Vue过滤器

代码:

Vue.filter('stringTodateTime', function ( dateTimeString ) {
if (!dateTimeString) return ''
return dateTimeString.replace(/_+/g, (_, n) => (n < 10) ? "/" : (n > 10) ? ":" : " ");
})

用法:

{{ 12_04_2021_12_59_34 | stringTodateTime }}

最新更新