在JavaScript中使用月/日/小时/分钟/秒

时间:2015-10-01 19:34:41

标签: javascript

你会如何重构这个?

	var myDate = new Date()
	var myYear = myDate.getFullYear()
	var myMonth = myDate.getMonth()
	if (myMonth < 10) {
		myMonth = '0' + myMonth
	}
	var myDay = myDate.getDate()
	if (myDay < 10) {
		myDay = '0' + myDay
	}
	var myHour = myDate.getHours()
	if (myHour < 10) {
		myHour = '0' + myHour
	}
	var myMinute = myDate.getMinutes()
	if (myMinute < 10) {
		myMinute = '0' + myMinute
	}
	var mySecond = myDate.getSeconds()
	if (mySecond < 10) {
		mySecond = '0' + mySecond
	}
document.getElementById('myDate').innerHTML = myYear + myMonth + myDay + myHour + myMinute + mySecond
<div id="myDate"></div>

1 个答案:

答案 0 :(得分:1)

使用moment.js库,您可以将格式规则缩减为一行。

有关详细信息,请参阅moment.js display Docs。请注意,现有代码存在差异:JavaScript存储0-11个月,意味着10月存储为9,而最有可能的是,我们希望显示&#34; 10&#34;。

&#13;
&#13;
var myDate = new Date();

document.getElementById('momentFormatted').innerHTML =
  moment(myDate).format("YYYYMMDDHHmmss");

var myYear = myDate.getFullYear()
var myMonth = myDate.getMonth()
if (myMonth < 10) {
  myMonth = '0' + myMonth
}
var myDay = myDate.getDate()
if (myDay < 10) {
  myDay = '0' + myDay
}
var myHour = myDate.getHours()
if (myHour < 10) {
  myHour = '0' + myHour
}
var myMinute = myDate.getMinutes()
if (myMinute < 10) {
  myMinute = '0' + myMinute
}
var mySecond = myDate.getSeconds()
if (mySecond < 10) {
  mySecond = '0' + mySecond
}
document.getElementById('myDate').innerHTML = myYear + myMonth + myDay + myHour + myMinute + mySecond
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<div id="myDate"></div>
<hr>
With Moment.js:
<div id="momentFormatted"></div>
&#13;
&#13;
&#13;