faqts : Computers : Programming : Languages : PHP : Function Libraries : Date and Time

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

36 of 61 people (59%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I work out the day of week from the (MySQL) date format YYYY-mm-dd?

Oct 3rd, 2002 14:52
Alex Dean, Nathan Wallace, Michael A. Smith


You can simply use MySQL to retrieve the dates in Unix timestamp format:
"SELECT UNIX_TIMESTAMP(somedate) as thedate WHERE somefield='somedata'"
If you are not using MySQL then we can still do the conversion in PHP:
The common underlying format used in any datetime translation is the
Unix timestamp. If I have (for example) a MySQL datetime
(YYYY-MM-DD HH:MM:SS) and want to get a day-of-the-week or something.
You need to convert the datetime to an Unix timestamp, then convert 
the timestamp to the day-of-the-week format.
The tools used for this are mktime() and date(). Starting from the MySQL
datetime, we need to use mktime to make an Unix timestamp. You can use
some
ereg() or substr() manipulation to get the YYYY, MM, DD, HH, MM and SS
values for your datetime value. e.g.:
$vardate = '2021-06-17 13:31:09';
ereg("([0-9]{4})-([0-9]{2})-([0-9]{2})
([0-9]{2}):([0-9]{2}):([0-9]{2})",
$vardate, $regs);
$dayofweek = date("D", mktime($regs[4], $regs[5], $regs[6], $regs[2],
$regs[3], $regs[1]));
print($dayofweek);
[A few steps are combined in the above code]
Since you can use MySQL to convert the datetime into an Unix timestamp,
you may never need to do this. BUT, if you get dates from other sources 
this may be helpful.
http://www.php.net/manual/ref.datetime.php3
***************************
You can also just do DAYOFWEEK(date).  See the MySQL manual section 6.3.4
--alex