Skip to content

Instantly share code, notes, and snippets.

@micah1701
Last active July 2, 2024 00:40
Show Gist options
  • Save micah1701/4120120 to your computer and use it in GitHub Desktop.
Save micah1701/4120120 to your computer and use it in GitHub Desktop.
Replicate PHP's native date() formatting in JavaScript for many common format types
/**
* Return a formated string from a date Object mimicking PHP's date() functionality
*
* format string "Y-m-d H:i:s" or similar PHP-style date format string
* date mixed Date Object, Datestring, or milliseconds
*
*/
function dateFormat(format,date){
if(!date || date === "")
{
date = new Date();
}
else if(typeof('date') !== 'object')
{
date = new Date(date.replace(/-/g,"/")); // attempt to convert string to date object
}
var string = '',
mo = date.getMonth(), // month (0-11)
m1 = mo+1, // month (1-12)
dow = date.getDay(), // day of week (0-6)
d = date.getDate(), // day of the month (1-31)
y = date.getFullYear(), // 1999 or 2003
h = date.getHours(), // hour (0-23)
mi = date.getMinutes(), // minute (0-59)
s = date.getSeconds(); // seconds (0-59)
for (var i = 0, len = format.length; i < len; i++) {
switch(format[i])
{
case 'j': // Day of the month without leading zeros (1 to 31)
string+= d;
break;
case 'd': // Day of the month, 2 digits with leading zeros (01 to 31)
string+= (d < 10) ? "0"+d : d;
break;
case 'l': // (lowercase 'L') A full textual representation of the day of the week
var days = Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
string+= days[dow];
break;
case 'w': // Numeric representation of the day of the week (0=Sunday,1=Monday,...6=Saturday)
string+= dow;
break;
case 'D': // A textual representation of a day, three letters
days = Array("Sun","Mon","Tue","Wed","Thr","Fri","Sat");
string+= days[dow];
break;
case 'm': // Numeric representation of a month, with leading zeros (01 to 12)
string+= (m1 < 10) ? "0"+m1 : m1;
break;
case 'n': // Numeric representation of a month, without leading zeros (1 to 12)
string+= m1;
break;
case 'F': // A full textual representation of a month, such as January or March
var months = Array("January","February","March","April","May","June","July","August","September","October","November","December");
string+= months[mo];
break;
case 'M': // A short textual representation of a month, three letters (Jan - Dec)
months = Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
string+= months[mo];
break;
case 'Y': // A full numeric representation of a year, 4 digits (1999 OR 2003)
string+= y;
break;
case 'y': // A two digit representation of a year (99 OR 03)
string+= y.toString().slice(-2);
break;
case 'H': // 24-hour format of an hour with leading zeros (00 to 23)
string+= (h < 10) ? "0"+h : h;
break;
case 'g': // 12-hour format of an hour without leading zeros (1 to 12)
var hour = (h===0) ? 12 : h;
string+= (hour > 12) ? hour -12 : hour;
break;
case 'h': // 12-hour format of an hour with leading zeros (01 to 12)
hour = (h===0) ? 12 : h;
hour = ( hour > 12) ? hour -12 : hour;
string+= (hour < 10) ? "0"+hour : hour;
break;
case 'a': // Lowercase Ante meridiem and Post meridiem (am or pm)
string+= (h < 12) ? "am" : "pm";
break;
case 'i': // Minutes with leading zeros (00 to 59)
string+= (mi < 10) ? "0"+mi : mi;
break;
case 's': // Seconds, with leading zeros (00 to 59)
string+= (s < 10) ? "0"+s : s;
break;
case 'c': // ISO 8601 date (eg: 2012-11-20T18:05:54.944Z)
string+= date.toISOString();
break;
default:
string+= format[i];
}
}
return string;
}
@50l3r
Copy link

50l3r commented Mar 18, 2020

Awesome function. Much thanks 4 share it :)

@zefir-git
Copy link

I created a fork, featuring the following extras:

  • Improved iteration
  • Better formatting
  • Rename function to date() to match name in PHP (does not override Date())
  • escaped characters are ignored (e.g. date("\\h h") -> "h 11")

Todo:

  • further code optimisation

@NikolasMeyer
Copy link

Shouldn't line 4 be as follows?
else if(typeof(date) !== 'object')

@ferdly
Copy link

ferdly commented Apr 19, 2021

Hi, I'm not up to writing a fork, but couldn't you make the first case as so:

case '\\': // '\\' is required for checking single back-slash
    i++;
    // console.log(format[i]);
    string+= format[i];
    break;

This supports (as does the original PHP function) "F j, Y \\a\\t g:i a"
Of course, in PHP you only need a single back-slash for a character, but I couldn't think of a way to avoid the double-back-slash adjustment.

@ferdly
Copy link

ferdly commented Apr 19, 2021

I am thrilled to have found this.

Thank You! BTW

Since I know that I am going to use this very much...
And since I am going to maintain my own implementation thereof...
And since I use a few configurations over and over...
And since I would otherwise be traveling to the PHP Documentation over and over...
I've added the following block at the very top of the function:

    //<supported Aliases>
    let formatAlias = format.toLowerCase();
    formatAlias = formatAlias === 'ddt' ? 'default date time' : formatAlias;
    formatAlias = formatAlias === 'dd' ? 'default date' : formatAlias;
    formatAlias = formatAlias === 'dt' ? 'default time' : formatAlias;
    format = formatAlias === 'default date time' ? "F j, Y, g:i a" : format;
    format = formatAlias === 'default date' ? "F j, Y" : format;
    format = formatAlias === 'default time' ? "g:i a" : format;
    format = formatAlias === 'course catalog date' ? 'l F j, Y' : format;
    format = formatAlias === 'calendar time' ? ''h:ia'' : format;
    //</supported Aliases>

Of course, this is very extensible.
FWIW $0.02

@Ebugo
Copy link

Ebugo commented Dec 30, 2021

I also created a fork of this gist (can be found here), where I touched these:

  • Made the code more readable (you can minify if you like)
  • Renamed the function to date() to match name in PHP
  • Added a check for if the date(timestamp) parameter provided is a number

Do check it out :)

@omar-aissani
Copy link

Great function thank you! although in line 14 there's a small mistake.
It must be:
else if(typeof(date) !== 'object')
Instead of:
else if(typeof('date') !== 'object')

@kubiqsk
Copy link

kubiqsk commented Jul 25, 2022

I was trying to find suitable solution for me and I ended up with writing my own
https://gist.github.com/kubiqsk/c60207a3075104df7cc1822a95053ecd

@dbareis
Copy link

dbareis commented Jul 1, 2024

I created a fork, featuring the following extras:

  • Improved iteration
  • Better formatting
  • Rename function to date() to match name in PHP (does not override Date())
  • escaped characters are ignored (e.g. date("\\h h") -> "h 11")

Todo:

  • further code optimisation

No longer exists

@dbareis
Copy link

dbareis commented Jul 2, 2024

The code by @kubiqsk handles these extra codes (missing from this implementation): "A, B, G, I, L, N, O, P, S, T, U, W, Z, e, o, r, t, v, z", however it doesn't handle escaped characters.

The follow code is an updated version of the above with suggested corrections above as well as handling escaped characters, if you don't care about escaped characters then I'd probably go with the kubiqsk one as it handles more codes.

/* Return a formatted string from a date Object mimicking PHP's date() functionality
 *
 * format  string  "Y-m-d H:i:s" or similar PHP-style date format string
 * date    mixed   Date Object, Datestring, or milliseconds
 *
 * NOTE
 * ~~~~~~~~~
 *     PHP: $today =       date('\i\t \i\s \t\h\e jS \d\a\y.');             // it is the 10th day.
 *      JS: today  = dateFormat('\\i\\t \\i\\s \\t\\h\\e jS \\d\\a\\y.');   // it is the 10 day.
 */
function dateFormat(format, date)
{
    if (!date || date === "")
        date = new Date();
    else if (typeof(date) !== 'object')
    {
        // attempt to convert string/number to date object
        try
        {
            if (typeof date === 'number')
               date = new Date(date);                    //timestamp
            else
               date = new Date(date.replace(/-/g, "/")); //probably string
        }
        catch (e)
        {
            date = new Date();                           //Can't handle whatever it was...
        }
    }

    var string = '',
        mo = date.getMonth(),   // month (0-11)
        m1 = mo+1,			    // month (1-12)
        dow = date.getDay(),    // day of week (0-6)
        d = date.getDate(),     // day of the month (1-31)
        y = date.getFullYear(), // 1999 or 2003
        h = date.getHours(),    // hour (0-23)
        mi = date.getMinutes(), // minute (0-59)
        s = date.getSeconds();  // seconds (0-59)

    for (var i = 0, len = format.length; i < len; i++) {
        switch(format[i])
        {
            case '\\': //Handle escaped characters
                i++;
                // console.log(format[i]);
                string+= format[i];
                break;
            case 'j': // Day of the month without leading zeros  (1 to 31)
                string+= d;
                break;

            case 'd': // Day of the month, 2 digits with leading zeros (01 to 31)
                string+= (d < 10) ? "0"+d : d;
                break;

            case 'l': // (lowercase 'L') A full textual representation of the day of the week
                var days = Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
                string+= days[dow];
                break;

            case 'w': // Numeric representation of the day of the week (0=Sunday,1=Monday,...6=Saturday)
                string+= dow;
                break;

            case 'D': // A textual representation of a day, three letters
                days = Array("Sun","Mon","Tue","Wed","Thr","Fri","Sat");
                string+= days[dow];
                break;

            case 'm': // Numeric representation of a month, with leading zeros (01 to 12)
                string+= (m1 < 10) ? "0"+m1 : m1;
                break;

            case 'n': // Numeric representation of a month, without leading zeros (1 to 12)
                string+= m1;
                break;

            case 'F': // A full textual representation of a month, such as January or March
                var months = Array("January","February","March","April","May","June","July","August","September","October","November","December");
                string+= months[mo];
                break;

            case 'M': // A short textual representation of a month, three letters (Jan - Dec)
                months = Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
                string+= months[mo];
                break;

            case 'Y': // A full numeric representation of a year, 4 digits (1999 OR 2003)
                string+= y;
                break;

            case 'y': // A two digit representation of a year (99 OR 03)
                string+= y.toString().slice(-2);
                break;

            case 'H': // 24-hour format of an hour with leading zeros (00 to 23)
                string+= (h < 10) ? "0"+h : h;
                break;

            case 'g': // 12-hour format of an hour without leading zeros (1 to 12)
                var hour = (h===0) ? 12 : h;
                string+= (hour > 12) ? hour -12 : hour;
                break;

            case 'h': // 12-hour format of an hour with leading zeros (01 to 12)
                hour = (h===0) ? 12 : h;
                hour = ( hour > 12) ? hour -12 : hour;
                string+= (hour < 10) ? "0"+hour : hour;
                break;

            case 'a': // Lowercase Ante meridiem and Post meridiem (am or pm)
                string+= (h < 12) ? "am" : "pm";
                break;

            case 'i': // Minutes with leading zeros (00 to 59)
                string+= (mi < 10) ? "0"+mi : mi;
                break;

            case 's': // Seconds, with leading zeros (00 to 59)
                string+= (s < 10) ? "0"+s : s;
                break;

            case 'c': // ISO 8601 date (eg: 2012-11-20T18:05:54.944Z)
                string+= date.toISOString();
                break;

            default:
                string+= format[i];
        }
    }

    return string;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment