Monday, March 5, 2018

System File 4: A javascript to handle date format differences between programming languages.

This java script makes sure the date is correctly interpreted between PHP and HTML. I found this on the web:

CODE
//<script>
/**
 * 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
 *
 * d-m-Y with leading zeroes
 * j-n-Y without leading zeroes
 *
 * dateFormat(d-m-Y, date), ex. date = 2-2-2017, and get 02-02-2017
 */
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 '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 'Y': // A full numeric representation of a year, 4 digits (1999 OR 2003)
string+= y;
break;
default:
string+= format[i];
}
}
return string;
}
}
//</script>
END CODE

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home