How do I get the day (1-7) from a Unix timestamp in PHP? I also need the day date (1-31) and month (1-12).
Asked
Active
Viewed 5.2k times
5 Answers
52
You can use date() function
$weekday = date('N', $timestamp); // 1-7
$month = date('m', $timestamp); // 1-12
$day = date('d', $timestamp); // 1-31

ahmetunal
- 3,930
- 1
- 23
- 26
-
This undoubtedly works. But date() has to calculate the actual date three times just to pick one element each time. If you need all three values anyway, isn't that a bit suboptimal? – chendral Mar 19 '10 at 08:24
-
6you can always use date('N.m.d etc.') at the same time for your purposes, i just gave the examples seperately to answer the question. – ahmetunal Mar 19 '10 at 09:10
-
The formats 'm' and 'd' return single digit numbers with leading zeros. It looks like the OP requested numbers without leading zeros ('j' and 'n' from @Dyllon's answer). – J.D. Sandifer Nov 13 '20 at 05:59
10
see http://docs.php.net/getdate
e.g.
$ts = time(); // could be any timestamp
$d=getdate($ts);
echo 'day of the week: ', $d['wday'], "\n";
echo 'day of the month: ', $d['mday'], "\n";
echo 'month: ', $d['mon'], "\n";

VolkerK
- 95,432
- 20
- 163
- 226
9
It's the date() function you're after.
You can get more details from the PHP manual but in a nutshell here are the functions you need.
date('N', $timestamp);
//numeric representation of the day of the week
date('j', $timestamp);
//Day of the month without leading zeros
date('n', $timestamp);
//Numeric representation of a month, without leading zeros

Dyllon
- 1,229
- 7
- 5
3
Use the date function as stated before, with your $timestamp
as the second argument:
$weekday = date('N', $timestamp); // 1 = Monday to 7 = Sunday
$month = date('m', $timestamp); // 1-12 = Jan-Dec
$day = date('d', $timestamp); // 1-31, day of the month
Not all PHP versions play nice with negative timestamps. My experience is that timestamps dating back to before the UNIX epoch fare better with the new DateTime object.

dyve
- 5,893
- 2
- 30
- 44
2
print "Week".date('N')."\n";
print "day of month " .date('d')."\n";
print "month ".date('m')."\n";

muruga
- 2,092
- 2
- 20
- 28