2009-09-13 116 views
0

我想要做的是在服务器上创建一个脚本,读取一个文本文件,对其进行排序,然后将其输出到一个javascript对象(可能通过JSON)。有问题的文本文件看起来是这样的:我应该如何在PHP中使用JavaScript存储日期?

 
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 

处理filereading的PHP是这样的:

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; 
    } 
} 

然而,存储UNIX在开始和结束日期timesstamps。我会使用DateTime类,但我目前仅限于PHP 4.4。理想情况下,我想存储在一个格式中的日期是:

  1. 可以比较的数字
  2. 是人类可读(允许dates.txt人编辑)
  3. 一贯格式(即“01-01 -1900" 转换为‘01/01/1900’)
  4. 可以转换为JavaScript Date对象

我怎么会去存储日期,所以他们satify这些限制?

回答

2

最安全的方法是使用UNIX时间戳

在JavaScript

,您可以使用

var mydate = new Date(); 
mydate.getTime(); //timestamp 
mydate.setTime(your_timestamp); //set using timestamp 

在PHP的日期函数将时间戳作为第二个参数。

看到http://jp.php.net/manual/en/function.date.phphttps://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Date

编辑:
还请参阅strftime http://jp.php.net/manual/en/function.strftime.php

编辑:
注:JavaScript函数采用毫秒,PHP函数使用秒。除以1000的JavaScript的输出或使用类似以下内容:

Date.prototype.getTimeInSeconds = function() { 
    return this.getTime()/1000; 
} 

var mydate = new Date(); 
mydate.getTimeInSeconds(); //PHP-compatible timestamp 
+0

你忘由1000到乘法/除法 – 2009-09-14 18:52:17

+0

你”再右吧。固定。 – 2009-09-15 00:01:40

0

商店的日期这样的:

19991231 = 1999年12月31日

20000704 = 2000年7月4日

人类可读,绝对可排序,并且您可以为转换创建JavaScript函数。

我将为您提供一个黑客从我精神错乱的头脑:

(假定x是YYYYMMDD形式的日期)

new Date((x-(x%10000))%9999,(((x%10000)-(x%100))%99)-1,x%100) 
相关问题