PHP day of week numeric to day of week text

It's not popular, but there's actually a function jddayofweek for this in PHP. You can call it with the second parameter as 1 to get full gregorian week day name or 2 for the abbreviated name.

e.g. jddayofweek(2, 2); #returns Wed

Note that for this function, numbers start at Monday. So Monday=0, Tuesday=1, ...


To get Sunday to Saturday from numeric day of the week 0 to 6:

//For example, our target numeric day is 0 (Sunday):
$numericDay = 0; //assuming current date('w')==0 and date('D')=='Sun';

Solution-1: Using PHP's built-in function jddayofweek() which starts from Monday whereas date('w') starts from Sunday:

jddayofweek($numericDay-1, 1); //returns 'Sun', here decreasing by '-1' is important(!)

//jddayofweek(0, 1); //returns 'Mon';
//jddayofweek(0, 2); //returns 'Monday';

Solution-2: Using a trick(!):

date('D', strtotime("Sunday +{$numericDay} days")); //returns 'Sun';

//date('l', strtotime("Sunday +{$numericDay} days")); //returns 'Sunday';

Create an array to map numeric DOWs to text DOWs.

$dowMap = array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');

If you need locale support, load the dow of some random date (epoch (0) would be a good date for example) and then for the next 6 days and build the dow map dynamically.


Bit of a hack, but:

$dow_text = date('D', strtotime("Sunday +{$dow_numeric} days"));

Tags:

Php

Date