JavaScript 获取当前日期和时间和时间戳的转换

深藏阁楼爱情的钟 2023-02-22 13:31 103阅读 0赞

var myDate = new Date();
Date.now()该方法返回当前时间距离1970年1月1日0点UTC的毫秒数
Math.round(new Date())精确到毫秒级
Math.round(new Date()/1000)精确到秒级
myDate.getYear();获取当前年份(2位)
myDate.getFullYear();获取完整的年份(4位,1970-???)
myDate.getMonth();获取当前月份(0-11,0代表1月)
myDate.getDate();获取当前日(1-31)
myDate.getDay();获取当前星期X(0-6,0代表星期天)
myDate.getTime();获取当前时间(从1970.1.1开始的毫秒数)
myDate.getHours();获取当前小时数(0-23)
myDate.getMinutes();获取当前分钟数(0-59)
myDate.getSeconds();获取当前秒数(0-59)
myDate.getMilliseconds();获取当前毫秒数(0-999)
myDate.toLocaleDateString();获取当前日期
var mytime=myDate.toLocaleTimeString();获取当前时间
myDate.toLocaleString();获取日期与时间

// 判断闰年

  1. Date.prototype.isLeapYear = function() {
  2. return (0==this.getYear()%4&&((this.getYear()%100!=0)||(this.getYear()%400==0)));
  3. }
  4. <script>
  5. //时间戳转换时间 格式"2020-01-01 12:00:00"
  6. // 添加一个flag参数,true返回当前时间,false返回传入的时间戳转换后的时间
  7. var timeTodate=function (time,flag) {
  8. var date;
  9. if(flag==true){
  10. date = new Date(time);
  11. }else{
  12. date = new Date(parseInt(time) * 1000);
  13. }
  14. Y = date.getFullYear() + '-';
  15. M = add0(date.getMonth() + 1) + '-';
  16. D = add0(date.getDate()) + ' ';
  17. h = add0(date.getHours()) + ':';
  18. m = add0(date.getMinutes()) + ':';
  19. s = add0(date.getSeconds());
  20. return Y + M + D + h + m + s;
  21. };
  22. //写一个函数判断是否给日期前添加0
  23. var add0=function(number){
  24. return number<10?'0'+number:number;
  25. }
  26. //获取当前时间戳
  27. var nowTime=Math.round(new Date()/1000)
  28. //一个月前时间计算
  29. var pevTime=nowTime-(60 * 60 * 24 * 30)
  30. //一个月前时间戳
  31. var pevMoth=timeTodate(pevTime,false);
  32. console.log(pevMoth)//=>'"2020-06-03 17:27:46"'
  33. </script>

发表评论

表情:
评论列表 (有 0 条评论,103人围观)

还没有评论,来说两句吧...

相关阅读