Reputation: 97591
What I want to do is make a script on the server read a text file, sort it, then output it to a javascript object (probably via JSON). The text file in question looks something like this:
13/09/2009,17/09/2009,Arbitrary dates 14/09/2009,18/09/2009,Some random comment 14/09/2010,18/12/2010,A comment to the dates 14/09/2010,18/09/2010,A subset of another date 14/09/2001,18/09/2002,The oldest date
The php to handle the filereading looks like this:
function loadDates()
{
$dateFile = fopen("dates.txt", "rt");
$dates = array();
if($dateFile)
{
flock($dateFile,LOCK_SH);
$i = 0;
while(!feof($dateFile))
{
$text = fgets($dateFile);
if($text !== FALSE)
{
$i++;
$arr = explode(",",$text,3);
//actual storage
$dates[$i]['start'] = strtotime($arr[0]);
$dates[$i]['end'] = strtotime($arr[1]);
$dates[$i]['comment'] = $arr[2];
}
}
fclose($dateFile);
//sort by start date, then by end date
foreach($dates as $key => $item)
{
$start[$key] = $item['start'];
$end[$key] = $item['end'];
}
array_multisort($start, SORT_ASC, $end, SORT_ASC, $dates);
return $dates;
}
else
{
return FALSE;
}
}
However, that stores unix timesstamps in the start and end dates. I would use the DateTime
class, but I'm currently restricted to PHP 4.4. Ideally, I'd like to store the dates in a format that:
dates.txt
)How would I go about storing the dates so they satify these restrictions?
Upvotes: 0
Views: 314
Reputation: 57167
The safest is to use UNIX timestamps
in javascript, you can use
var mydate = new Date();
mydate.getTime(); //timestamp
mydate.setTime(your_timestamp); //set using timestamp
in php the date function takes the timestamp as second parameter.
see http://jp.php.net/manual/en/function.date.php and https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Date
EDIT:
Also see strftime http://jp.php.net/manual/en/function.strftime.php
EDIT:
Note: the javascript function takes milliseconds, and the php functions use seconds. divide the output of the javascript by 1000 or use something like the following:
Date.prototype.getTimeInSeconds = function() {
return this.getTime()/1000;
}
var mydate = new Date();
mydate.getTimeInSeconds(); //PHP-compatible timestamp
Upvotes: 2
Reputation: 1947
Store the dates thus:
19991231 = Dec. 31, 1999
20000704 = July 4, 2000
Human readable, definitely sortable, and you can make a JavaScript function for the conversion.
I will provide you with a hack from my deranged mind:
(this assumes that x is that date in yyyymmdd form)
new Date((x-(x%10000))%9999,(((x%10000)-(x%100))%99)-1,x%100)
Upvotes: 0