Home  >  Article  >  Web Front-end  >  Detailed explanation of time format processing in JavaScript

Detailed explanation of time format processing in JavaScript

零下一度
零下一度Original
2017-07-23 10:42:111606browse

写这篇文章,总结一下前端JavaScript遇到的时间格式处理。

1 C#时间戳处理

从后台返回的C#时间为:/Date(-62135596800000)/,这个是C#的DateTime.MinValue; 要在html页面展示,一个方法是后端先处理成yyyy-MM-dd HH:mm:ss的格式,前端直接展示。 如果后端不做处理,就需要前端来做处理了,下面就是看前端处理的这种情况。

代码如下:

// 说明:将C#时间戳,格式为:/Date(-62135596800000),转换为js时间。// 参数:timeSpan 字符串 例如:'/Date(-62135596800000)'// 结果:JS的Datevar parseDate = function(timeSpan)
{    var timeSpan = timeSpan.replace('Date','').replace('(','').replace(')','').replace(/\//g,'');    var d = new Date(parseInt(timeSpan));    return d;
};

2 JS时间格式化处理

2.1转换为:yyyy-MM-dd HH:mm:ss格式

代码如下:

// 说明:JS时间Date格式化参数// 参数:格式化字符串如:'yyyy-MM-dd HH:mm:ss'// 结果:如2016-06-01 10:09:00Date.prototype.Format = function (fmt) { //author: meizz     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()      };    var year = this.getFullYear();    var yearstr = year + '';    yearstr = yearstr.length >= 4 ? yearstr : '0000'.substr(0, 4 - yearstr.length) + yearstr;        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (yearstr + "").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;}

JavaScript简单日期代码:

<script>
var dt=new Date();
var year=dt.getFullYear();
var month=dt.getMonth()+1;
var date=dt.getDate();
var day=dt.getDay();
var dayColl=[&#39;星期一&#39;,&#39;星期二&#39;,&#39;星期三&#39;,&#39;星期四&#39;,&#39;星期五&#39;,&#39;星期六&#39;,&#39;星期日&#39;];
var riqi=year+"年"+month+"月"+date+"日";
var xingqi=dayColl[day-1];
$(function(){
$("#date").html(riqi);
$("#date").next().html(xingqi);
});
</script>


The above is the detailed content of Detailed explanation of time format processing in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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