Page 1 of 1

[Challenge] The exact date (date representation challenge)

Posted: Sat Jul 03, 2010 8:45 am
by Darhazer
In MS Excel, date value is stored in number of days since 1.1.1900
Write a function that accept integer (numer of days) and returns the exact date. Note the leap years.

So, to check your program:

1 should return 1 Jan 1900 (so we start counting from 1)
14600 should return 22 Dec 1939
21961 should return 16 Feb 1960
40361 should return 3 Jul 2010 :)

edit: corrected the expected result for 21961

Re: [Challenge] The exact date (date representation challeng

Posted: Sat Jul 03, 2010 9:17 am
by Apollo

Code: Select all

<?php
if ($d=intval($_POST['d']))
{
  $dm = $d;
  for ($y=1900;;$y++)
  {
    $ly = !($y&3) && (($y%100) || !($y%400));
    $nd = $ly ? 366 : 365;
    if ($dm<=$nd) break;
    $dm -= $nd;
  }
  if ($ly) $dm += 365*2;
  $dm = date('j M',($dm*24-12)*60*60);
  print("Day number $d is $dm $y<hr>");
}
?>
<form method='post'>Enter day number: <input type='text' name='d'> <input type='submit'></form>
Oh and 21961 should return 16 Feb 1960 ;)

Re: [Challenge] The exact date (date representation challeng

Posted: Sat Jul 03, 2010 11:51 am
by AbraCadaver

Code: Select all

function exact_date($days) {
	//$date = new DateTime('1899-12-31');  //use for your timezone
        $date = new DateTime('1899-12-31', new DateTimeZone('UTC'));  //use for specific timezone
	$date->modify("+$days days");
	return $date->format('j M Y');
}

foreach(array(0,1,14600,21961,40361) as $days) {
	echo exact_date($days)."\n";
}
[text]31 Dec 1899
1 Jan 1900
22 Dec 1939
16 Feb 1960
3 Jul 2010[/text]

Re: [Challenge] The exact date (date representation challeng

Posted: Sat Jul 03, 2010 12:33 pm
by Apollo
AbraCadaver wrote:DateTime
Oh, right.. THAT was the class for dealing with timestamps before 1970 ;)

Re: [Challenge] The exact date (date representation challeng

Posted: Sat Jul 03, 2010 12:38 pm
by Darhazer
Apollo wrote: Oh and 21961 should return 16 Feb 1960 ;)
Well, Excel thinks that 1900 is a leap year :lol:

Re: [Challenge] The exact date (date representation challeng

Posted: Sat Jul 03, 2010 1:09 pm
by AbraCadaver
Darhazer wrote:
Apollo wrote: Oh and 21961 should return 16 Feb 1960 ;)
Well, Excel thinks that 1900 is a leap year :lol:
http://support.microsoft.com/kb/214326

Re: [Challenge] The exact date (date representation challeng

Posted: Sun Jul 04, 2010 7:56 am
by Weirdan
Darhazer wrote: Well, Excel thinks that 1900 is a leap year :lol:
Well, then your other dates were off. Interestingly, to correct for this bug google spreadsheets start counting from 1899-12-31