简体   繁体   中英

Convert Number to Day of Week

I need to convert a number to a date ie

1 -> Sunday
2 -> Monday

I have the following question which aids with the opposite: day of the week to day number (Monday = 1, Tuesday = 2)

Once I am able to do this I could for example loop through and echo the day ie:

while($i < 7)
{
    echo date("N",strtotime(1));
}

Everything I am searching for seems to be people asking to convert a day to a number. Can someone please point me in the right direction

Just put the days in an array using the day of the week as the key. Then use date('N') to get the day of the week and use that as they key to access that array value.

$days = [
  1 => 'Sunday',
  2 => 'Monday',
  3 => 'Tuesday',
  4 => 'Wednesday',
  5 => 'Thursday',
  6 => 'Friday',
  7 => 'Saturday'
];

echo $days[date('N')];

You just need to create an Array to do that, Please check this :

$dayOfWeek = array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
echo $dayOfWeek[2]."<br />";
echo $dayOfWeek[8%7];
echo $dayOfWeek[date('N')];

Why I write an array like that ? index 0 => "Sunday" and 1 => "Monday" .... ? Because if it's a day you must todo that, 1 week is 7 day so the rest you can use "Modulo / %(in php)" to convert that.

For example : If date 1 March 2015 is Sunday so the day 8 must be Monday because 8 mod 7 is 1 or 8%7 (in php) is 1 . So to convert that you just do this $dayOfWeek[8%7] to get the dayOfWeek. :)

For another conditional case you need your logic to do that. If day 1 May 2015 is Friday. Just keep in mind to check the year it was to know the February day count is 28 or 29.

How to check ? please try this :

$year = 2015;
$feb = (($year%100)and !($year%4)or !($year%400))+28;
echo $feb;

Day in year should like this :

$month= array(0,31,$feb,31,30,31,30,31,31,30,31,30,31);

0=0, 1=January,2=February,....

Hope this help you out.. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM