我如何转换以下日期格式(Mon Nov 19 13:29:40 2012)
成:
日/月/年
<html>
<head>
<script type="text/javascript">
function test(){
var d = Date()
alert(d)
}
</script>
</head>
<body>
<input onclick="test()" type="button" value="test" name="test">
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
mae*_*ics 151
一些JavaScript引擎可以直接解析该格式,这使得任务非常简单:
function convertDate(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat)
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')
}
console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"Run Code Online (Sandbox Code Playgroud)
Tre*_*xon 36
这将确保您获得两位数的日期和月份.
function formattedDate(d = new Date) {
let month = String(d.getMonth() + 1);
let day = String(d.getDate());
const year = String(d.getFullYear());
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return `${day}/${month}/${year}`;
}
Run Code Online (Sandbox Code Playgroud)
或者说:
function formattedDate(d = new Date) {
return [d.getDate(), d.getMonth()+1, d.getFullYear()]
.map(n => n < 10 ? `0${n}` : `${n}`).join('/');
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
316547 次 |
| 最近记录: |