Home > Web Front-end > JS Tutorial > body text

How to convert numbers to time in JavaScript

藏色散人
Release: 2021-07-01 11:10:32
Original
9018 people have browsed it

JavaScript将数字转换成时间的方法:首先把字符串进行日期的封装;然后封装转换函数;最后调用函数“date.Format("yyyy-MM-dd hh:mm:ss");”即可。

How to convert numbers to time in JavaScript

本文操作环境:windows7系统、javascript1.8.5版,DELL G3电脑

JavaScript怎么将数字转换成时间?

js将 一串数字1403149534转换为日期格式

   js中接收到后台返回的json字符串中的日期类型的字段都变成了一串数字,形如:1500341149000。所以我们需要将这个串格式化形如:2017-07-18 09:25:49.

   直接上代码:

    1、先把字符串进行日期的封装 var date = new Date(1500341149000);

    2、封装转换函数

 

Date.prototype.Format = function(fmt)   
{ 
//author:wangweizhen
  var o = {   
    "M+" : this.getMonth()+1,                 //月份   
    "d+" : this.getDate(),                    //日
    "h+" : this.getHours(),                   //小时   
    "m+" : this.getMinutes(),                 //分   
    "s+" : this.getSeconds(),                 //秒   
    "q+" : Math.floor((this.getMonth()+3)/3), //季度   
    "S"  : this.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt))   
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));   
  for(var k in o)   
    if(new RegExp("("+ k +")").test(fmt))   
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
  return fmt;   
};
Copy after login

   3、调用函数格式化:date.Format("yyyy-MM-dd hh:mm:ss");

  这样就可以完成转换了,献给需要的朋友,这是前台格式化,那么我们是否能在转转换json之前进行一些操作,

得到我们想要的格式呢,也就是这个转换操作放在后台来做,有好的想法的读者可以交流。

推荐学习:《javascript高级教程

The above is the detailed content of How to convert numbers to time in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!