温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在jQuery中对时间戳和日期进行转换

发布时间:2021-02-24 17:35:06 来源:亿速云 阅读:225 作者:Leah 栏目:web开发

怎么在jQuery中对时间戳和日期进行转换?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

具体如下:

(function($) {
    $.extend({
      myTime: {
        /**
         * 当前时间戳
         * @return <int>  unix时间戳(秒)
         */
        CurTime: function(){
          return Date.parse(new Date())/1000;
        },
        /**
         * 日期 转换为 Unix时间戳
         * @param <string> 2014-01-01 20:20:20 日期格式
         * @return <int>  unix时间戳(秒)
         */
        DateToUnix: function(string) {
          var f = string.split(' ', 2);
          var d = (f[0] ? f[0] : '').split('-', 3);
          var t = (f[1] ? f[1] : '').split(':', 3);
          return (new Date(
              parseInt(d[0], 10) || null,
              (parseInt(d[1], 10) || 1) - 1,
              parseInt(d[2], 10) || null,
              parseInt(t[0], 10) || null,
              parseInt(t[1], 10) || null,
              parseInt(t[2], 10) || null
            )).getTime() / 1000;
        },
        /**
         * 时间戳转换日期
         * @param <int> unixTime 待时间戳(秒)
         * @param <bool> isFull 返回完整时间(Y-m-d 或者 Y-m-d H:i:s)
         * @param <int> timeZone 时区
         */
        UnixToDate: function(unixTime, isFull, timeZone) {
          if (typeof (timeZone) == 'number')
          {
            unixTime = parseInt(unixTime) + parseInt(timeZone) * 60 * 60;
          }
          var time = new Date(unixTime * 1000);
          var ymdhis = "";
          ymdhis += time.getUTCFullYear() + "-";
          ymdhis += ((time.getUTCMonth()+1) < 10 ? "0" + (time.getUTCMonth()+1) : (time.getUTCMonth()+1)) + "-";
          ymdhis += (time.getUTCDate() < 10 ? "0" + time.getUTCDate() : time.getUTCDate()) + " ";
          ymdhis += (time.getHours() < 10 ? "0" + time.getHours() : time.getHours()) + ":";
          ymdhis += (time.getUTCMinutes() < 10 ? "0" + time.getUTCMinutes() : time.getUTCMinutes()) + ":";
          ymdhis += (time.getUTCSeconds() < 10 ? "0" + time.getUTCSeconds() : time.getUTCSeconds());
          if (isFull === true)
          {
            ymdhis += (time.getHours() < 10 ? "0" + time.getHours() : time.getHours()) + ":";
            ymdhis += (time.getUTCMinutes() < 10 ? "0" + time.getUTCMinutes() : time.getUTCMinutes()) + ":";
            ymdhis += (time.getUTCSeconds() < 10 ? "0" + time.getUTCSeconds() : time.getUTCSeconds());
          }
          return ymdhis;
        }
      }
    });
})(jQuery);

调用方法:

<script>
  document.write($.myTime.DateToUnix('2017-08-07 10:49:59')+'<br>');
  document.write($.myTime.UnixToDate(1502085303));
</script>

关于怎么在jQuery中对时间戳和日期进行转换问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI