Skip to content

Instantly share code, notes, and snippets.

@tonylegrone
Created December 12, 2012 18:56
Show Gist options
  • Save tonylegrone/4270524 to your computer and use it in GitHub Desktop.
Save tonylegrone/4270524 to your computer and use it in GitHub Desktop.
Provides a new method to the Date object with properties similar to PHP. Not all PHP date options were ported for the sake of not duplicating too many methods already available.
// Pad a number with zeros to specified length.
Number.prototype.pad = function(length)
{
var str = '' + this.valueOf();
while (str.length < length) {
str = '0' + str;
}
return str;
}
// Mimics php date() function. See http://php.net/manual/en/function.date.php
// Requires Number.pad() method.
Date.prototype.getDateAdv = function()
{
// Day
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var dayLong = days[this.getDay()];
this.N = this.getDay() + 1;
this.w = this.getDay();
this.d = this.getDate().pad(2);
this.j = this.getDate();
this.l = dayLong;
this.D = dayLong.substr(0, 3);
// Month
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
var monthLong = months[this.getMonth()];
this.n = this.getMonth() + 1;
this.m = (this.getMonth() + 1).pad(2);
this.F = monthLong;
this.M = monthLong.substr(0, 3);
// Year
this.Y = this.getFullYear();
this.y = this.getFullYear().toString().substr(2, 2);
// Time
var a = (this.getHours() < 12)? 'am':'pm';
var g = (this.getHours() <= 12)? this.getHours():this.getHours() - 12;
this.a = a;
this.A = a.toUpperCase();
this.g = g;
this.G = this.getHours();
this.h = g.pad(2);
this.H = this.getHours().pad(2);
this.i = this.getMinutes().pad(2);
this.s = this.getSeconds().pad(2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment