Go to comments

js 时间戳转 PHP 时间戳

PHP 时间戳


PHP 获取时间戳用 time() 方法,获取的时间戳是按照秒计算的,也是 UNIX 的时间戳,长度是 10 位数字

$time = time();

echo $time;


先将时区设置为零时区,在获取时间戳

date_default_timezone_set('GMT');

$time = time();

echo $time;


js 时间戳


Date.getTime()

js 获取时间戳用 Date 对象上的 getTime() 方法,是按照毫秒计算的,长度是 13 位数字

var nowTime = new Date().getTime(); 

console.log(nowTime); // js时间


如何将 js 的时间戳转成 PHP 的时间戳?

js 的时间戳 / 1000,在用 parseInt 取整,经测试和 PHP 同时获取的时间戳几乎一样

var nowTime = new Date().getTime(); 

console.log(parseInt(nowTime/1000)); // js时间戳转为PHP时间


也可以用 Math.round 方法取整,有时候和 PHP 获取的有一两秒的差别

var nowTime = Math.round(new Date().getTime()/1000);

console.log(nowTime); // 将js时间戳转为PHP时间戳


格式化 js 时间戳,比如 1981-06-14 12:32:38,该方法来自于渡一教育袁老师 vue 课程

function formatDate(timestamp, showTime = false){
  // 年月日
  const date = new Date(+timestamp);
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  // 时分秒
  const hour = date.getHours().toString().padStart(2, "0");
  const minute = date.getMinutes().toString().padStart(2, "0");
  const second = date.getSeconds().toString().padStart(2, "0");
  // 拼接年-月-日
  let str = `${date.getFullYear()}-${month}-${day}`;
  // 拼接时:分:秒
  if(showTime){
    str += ` ${hour}:${minute}:${second}`;
  }
  return str;
}


附,一些网址

https://www.cnblogs.com/websjs/p/5903554.html   php与js时间戳相互转换

https://blog.csdn.net/weixin_30852419/article/details/96728814   date_default_timezone_set()设置时区

https://www.php.cn/xiazai/tool/5     Unix时间戳转换工具

http://c.biancheng.net/view/7468.html     PHP time()获取当前时间戳

https://www.php.cn/php-weizijiaocheng-423422.html  php时间戳转换

https://cloud.tencent.com/developer/information/js%E5%B0%86%E6%97%B6%E9%97%B4%E6%88%B3%E8%BD%AC%E6%8D%A2%E4%B8%BA%E6%97%B6%E9%97%B4%E6%A0%BC%E5%BC%8F-salon


Leave a comment 0 Comments.

Leave a Reply

换一张