JavaScript 实现 PHP strtotime 与 date 功能的时间戳转换方法

作者:阿沐

时间:2026-10-29

浏览:495

本文介绍如何在 JavaScript 中模拟 PHP 的 strtotime() 和 date() 函数功能。通过自定义函数实现日期字符串与 Unix 时间戳的双向转换,并演示如何格式化输出为 'YYYY-MM-DD HH:mm:ss' 格式,适用于需要兼容 PHP 逻辑的前端开发场景。

文章目录

JavaScript 时间戳转换概述

本文详细介绍一种在 JavaScript 中模拟 PHP 内置函数 strtotime() 和 date() 功能的实现方案,供开发者参考使用。

由于原生 JavaScript 缺乏直接对应 PHP strtotime() 和 date() 的内置方法,无法直接进行时间戳的便捷转换,因此需要自定义函数来补充这一功能。

核心转换函数实现


function datetime_to_unix(datetime){ 
  var tmp_datetime = datetime.replace(/:/g,'-'); 
  tmp_datetime = tmp_datetime.replace(/ /g,'-'); 
  var arr = tmp_datetime.split("-"); 
  var now = new Date(Date.UTC(arr[0],arr[1]-1,arr[2],arr[3]-8,arr[4],arr[5])); 
  return parseInt(now.getTime()/1000); 
} 
function unix_to_datetime(unix) { 
  var now = new Date(parseInt(unix) * 1000); 
  return now.toLocaleString().replace(/年|月/g, "-").replace(/日/g, " "); 
} 
var datetime = '2012-11-16 10:36:50'; 
var unix = datetime_to_unix(datetime); 
document.write(datetime+' 转换后的时间戳为: '+unix+' 
'); 
var unix = 1353033300; 
var datetime = unix_to_datetime(unix); 
document.write(unix+' 转换后的日期为: '+datetime);

日期格式化输出

若需生成类似 '2010-10-20 10:00:00' 的标准日期时间格式,可通过特定的格式化逻辑轻松实现。

本地时间格式化示例


<script>
function getLocalTime(nS) {
  return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " "); 
}
alert(getLocalTime(1177824835));
</script>

完整交互示例

以下是完整的代码示例。

综合应用代码


<script type="text/javascript">
var day1 = parseInt(new Date().valueOf()/1000);
var day2 = new Date(day1 * 1000);
function getLocalTime(nS) { 
  return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:d{1,2}$/,' '); 
}
/* 同上面函数 */
function getLocalTimes(nS) { 
  return new Date(parseInt(nS) * 1000).toLocaleString().substr(0,17);
} 
function getLocalFormatTime(nS) { 
 return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");  
}
document.getElementById("btn1").onclick = function(){
 alert(day1);
}
document.getElementById("btn2").onclick = function(){
 alert(day2.toLocaleString());
}
document.getElementById("btn3").onclick = function(){
 alert( getLocalTime(day1) );
}
document.getElementById("btn4").onclick = function(){
 alert( getLocalFormatTime(day1) );
}
document.getElementById("btn5").onclick = function(){
 alert(day2.getFullYear()+"-"+(day2.getMonth()+1)+"-"+day2.getDate()+" "+day2.getHours()+":"+day2.getMinutes()+":"+day2.getSeconds());
}
</script>

希望上述内容能对各位在 JavaScript 程序设计中的时间处理有所帮助。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章