JavaScript - PHP-Styled Date Function

 

The phpDate() function mimics PHP's date() function, which is a lot easier to use than the standard JavaScript date functions. My script supports most of the options that PHP supports, the options are listed at the bottom.

If you want a month/day/year combination, simply use:

  1. alert(phpDate('m/d/Y',new Date()));

Code: Attached

Example:

  1. <pre id="dt"></pre>
  2. <script type="text/javascript">
  3. var x = new Date();
  4. document.getElementById('dt').innerHTML += '\nDay : '+ phpDate('d|D|j|l|N|S|w|z',x);
  5. document.getElementById('dt').innerHTML += '\nWeek : '+ phpDate('W',x);
  6. document.getElementById('dt').innerHTML += '\nMonth : '+ phpDate('F|m|M|n|t',x);
  7. document.getElementById('dt').innerHTML += '\nYear : '+ phpDate('L|Y|y',x);
  8. document.getElementById('dt').innerHTML += '\nTime : '+ phpDate('a|A|g|G|h|H|i|s|u',x);
  9. document.getElementById('dt').innerHTML += '\nTime Zone : '+ phpDate('O|P|T|Z',x);
  10. document.getElementById('dt').innerHTML += '\nFull Date/Time: '+ phpDate('c|r|U',x);
  11. </script>

Supported options:
Day
d - 01 to 31
D - Mon through Sun
j - 1 to 31
l - Sunday through Saturday
N - 1 (for Monday) through 7 (for Sunday)
S - st, nd, rd or th. Works well with j
w - 0 (for Sunday) through 6 (for Saturday)
z - 0 through 365
x - Days in this month (non-PHP option)
Week
W - Example: 42 (the 42nd week in the year)
Month
F - January through December
m - 01 through 12
M - Jan through Dec
n - 1 through 12
t - 28 through 31 (days in month)
Year
L - 1 if it is a leap year, 0 otherwise.
Y - Examples: 1999 or 2003
y - Examples: 99 or 03
Time
a - am or pm
A - AM or PM
g - 1 through 12
G - 0 through 23
h - 01 through 12
H - 00 through 23
i - Minutes 00 to 59
s - Seconds 00 through 59
u - Miliseconds
Timezone
O - Example: +0200
P - Example: +02:00
T - Examples: EST, MDT ...
Z - Timezone offset in seconds. -43200 through 50400
Full Date/Time
c - ISO 8601 Date 2004-02-12T15:19:21+00:00
r - RFC 2822 formatted date - Thu, 21 Dec 2000 16:01:07 +0200
U - Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)

AttachmentSize
phpDate.js.gz1.83 KB