如何用UNIX时间戳替换人类可读的日期字符串?


How can I replace human-readable date strings with UNIX timestamps?

我有一个非常大的txt文件javascript数组-太大了,我去分别编辑每个条目。它看起来像这样:

["12/1/2011 00:00",15848],["12/1/2011 01:00",15108],["12/1/2011 02:00",14643],["12/1/2011 03:00",14265], &c.

我如何通过PHP传递这个文件来改变所有的日期并写一个新文件?我想我需要使用strptime()strtotime(),但我不确定如何进行。

日期格式为Month/Day/Year

编辑:我最终从CSV文件中重新创建了数组。这是我使用的代码,以防有人感兴趣。谢谢你的帮助。

$handle = fopen("stuff.csv", "r");
while(($data = fgetcsv($handle, ",")) !== FALSE) {
    echo "[" . strtotime($data[0]) . ", " . $data[1] . "],<br />";
}

用正则表达式匹配字符串中的所有日期,然后对结果使用strtotime():

$str = '["12/1/2011 00:00",15848],["12/1/2011 01:00",15108],["12/1/2011 02:00",14643],["12/1/2011 03:00",14265]';
$p = '#('d+/'d+/'d{4}'s'd{2}:'d{2})#';
preg_match_all($p, $str, $matches);
foreach ($matches[1] as $m) {
  echo strtotime($m) . "'n";
}

UPDATE:刚刚意识到你说你的数据是在一个javascript数组。你也可以在JS中轻松地处理这个问题:

var new_times = [];
var times = [["12/1/2011 00:00",15848],["12/1/2011 01:00",15108],["12/1/2011 02:00",14643],["12/1/2011 03:00",14265]];
for(i=0; i < times.length; i++) {
  var d = new Date(times[i][0]);
  var new_arr = [(d.getTime() / 1000), times[i][1]];
  new_times.push(new_arr);
}

javascript

var times = [["12/1/2011 00:00",15848],["12/1/2011 01:00",15108],["12/1/2011 02:00",14643],["12/1/2011 03:00",14265]];
//var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
for(i in times) {
    var time = times[i][0].split(/'/|'s|:/i);
    console.log(time);
    date = new Date(time[2], time[0], time[1], time[3], time[4]);
    console.log(date.getTime());
}