Page 1 of 1

Get the date, year and day of the week using PHP Rate Topic: -----

#1 paperclipmuffin  Icon User is offline

  • Disassembling...
  • member icon

Reputation: 13
  • View blog
  • Posts: 944
  • Joined: 16-April 09

Posted 20 August 2009 - 12:11 AM

Hello all,

You will often see on websites something like:

Quote

Tuesday, 25th August, 2009, 3:33 PM


Today, we will do something a lot like that. First, let's find out the time using php:

$tim = time();



So that $tim is the time. Now for date:

$dat = date();



And the year we know.

$year = '2009';



Just go through and change that every year.

Now for the clever bit

We'll find the day of the week using this algorithm:

day = (date + y + [31m / 12] + [y / 4] - [y / 100] + [y / 400])MOD7

Beauty, eh?

Now I'll go through that with you for all our less maths-oriented coders.

day & date: Pretty self explanatory.

y: Year (pretty obvious too).

m: The number of the month; eg November = 11, February = 2.

[ square brackets]: INT, Integer division; AKA throw away everything after the decimal point, once you've done the stuff inside, just like normal brackets.

MOD: Modular division, the evil twin of INT. Keep everything after the decimal point.

Now this translates into PHP as:

$day = ($date + $year + (variant_int(31 * $m_int / 12)) + (variant_int($year / 4)) - (variant_int($year / 100)) + (variant_int($year / 400))) % 7;



Phew, anyway, use this to get $day. Unfortunately, this is an integer from 0 - 6, not a day yet. Well, we'll sort that stuffy integer out with a giant big if:

$day_string = '';
if($day == 0){
	$day_string = 'Sunday';
}
if($day == 1){
	$day_string = 'Monday';
}
if($day == 2){
	$day_string = 'Tuesday';
}
ect, ect...



So we can now have our finished product!

$product = $day_string.', '.$dat.', '.$tim;



Cool!

Well, we had our fun, but this tutorial has come to an end, so enjoy your new knowledge, and see you next tutorial! :)

~PaperClip Muffin

Is This A Good Question/Topic? 0
  • +

Page 1 of 1