Home  >  Article  >  Web Front-end  >  js时间戳格式化成日期格式的多种方法_javascript技巧

js时间戳格式化成日期格式的多种方法_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:16:161229browse

js需要把时间戳转为为普通格式,一般的情况下可能用不到的,
下面先来看第一种吧

复制代码 代码如下:

function getLocalTime(nS) {
return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/,' ');
}
alert(getLocalTime(1293072805));

结果是
2010年12月23日 10:53
第二种
复制代码 代码如下:

function getLocalTime(nS) {
return new Date(parseInt(nS) * 1000).toLocaleString().substr(0,17)}
alert(getLocalTime(1293072805));

如果你想得到这样格式的怎么办呢?
2010-10-20 10:00:00
看下面代码吧
复制代码 代码如下:

function getLocalTime(nS) {
return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
}
alert(getLocalTime(1177824835));

也可以这样写的
复制代码 代码如下:

function formatDate(now) {
var year=now.getYear();
var month=now.getMonth()+1;
var date=now.getDate();
var hour=now.getHours();
var minute=now.getMinutes();
var second=now.getSeconds();
return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;
}
var d=new Date(1230999938);
alert(formatDate(d));

好了问题解决
需要注意的是
不要把字符串中的Date(这样的字符也传进去,要先处理一下,这样很方便 就能处理的
可以使用replace方法
如下:
复制代码 代码如下:

replace("/Date(","").replace(")/","");
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