Phillip Senn
Phillip Senn

Reputation: 47605

Working with month/day/hours/minutes/seconds in JavaScript

How would you refactor this?

	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>

Upvotes: 0

Views: 47

Answers (1)

Heitor Chang
Heitor Chang

Reputation: 6057

With the moment.js library, you can reduce the formatting rules to a single line.

See the moment.js display Docs for details. Note that there is an difference with the existing code: JavaScript stores months from 0-11, meaning October is stored as 9, while most likely, we want to show "10".

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
<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>

Upvotes: 1

Related Questions