Moment Date Examples
Some moment.js date examples
by Riffic
HTML
<script src="https://raw.github.com/timrwood/moment/1.7.2/min/moment.min.js"></script>
JavaScript
var y = 2013,
m = 0,
d = 30;
var d1 = new Date( y, m, d );
var m1 = moment( [y, m, d] );
var m2 = moment( [y, m, d] );
console.log("Moment 1: ", m1.toDate() );
console.log("Moment 2: ", m1.add("months", 1).toDate() );
console.log("Moment 3: ", m1.add("months", 1).toDate() );
//toDate comparison test, ie use new Date( m1.toDate().getTime() ) to generate unique
console.log("Moment 3: ", m1.toDate() === m1.toDate() );
console.log("Moment 4: ", new Date( m1.toDate() ) === m1.toDate() );
//Simply passes reference to date, modifying date in moment, modifies date outside
console.log("Moment 5: ", moment( d1 ).toDate() === d1 );
function weekOfMonth(){
var firstDay = new Date(this.year(), this.month(), 1).getDay();
return Math.ceil((this.date() + firstDay)/7);
}
function weekOfMonthBetter(){
var firstDay = new Date( this.toDate().getTime() );
firstDay.setDate(1);
firstDay = firstDay.getDay();
return Math.ceil((this.date() + firstDay)/7);
}
console.time("weekTest1");
var momTest = moment( m1 );
for( i = 0; i < 1000000; i++ ){
weekOfMonth.apply( momTest );
}
console.timeEnd("weekTest1");
console.log("week: ", weekOfMonth.apply( momTest) );
console.time("weekTest2");
var momTest = moment( m1 );
for( i = 0; i < 1000000; i++ ){
weekOfMonthBetter.apply( momTest );
}
console.timeEnd("weekTest2");
console.timeEnd("weekTest3");