JavaScript 实现 PHP strtotime 与 date 功能的时间戳转换方法
作者:阿沐时间:2026-10-29 13:34:08浏览:496
本文介绍如何在 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 程序设计中的时间处理有所帮助。
作者最新文章
为什么叫JavaScript:语言命名由来及与Java的历史渊源
2026-11-05 11:37:48
JS获取当前时间年月日时分秒并格式化为YYYY-MM-DD HH:mm:ss
2026-11-04 21:25:21
不同语言间JS与Java/Python加密结果不一致怎么办
2026-11-04 18:27:23
Mock.js 拦截 Axios 和 Fetch 请求的原理与配置方法
2026-11-04 08:13:59
JS怎么获取当前日期并格式化为YYYY-MM-DD
2026-11-03 18:47:03
相关标签:
