js时间戳与日期格式互转!!

js时间戳转为日期格式

什么是Unix时间戳(Unix timestamp): Unix时间戳(Unix timestamp),或称Unix时间(Unix time)、POSIX时间(POSIX time),是一种时间表示方式,定义为从格林威治时间1970年01月01日00时00分00秒起至现在的总秒数。Unix时间戳不仅被使用在Unix系统、类Unix系统中,也在许多其他操作系统中被广泛采用。

目前相当一部分操作系统使用32位二进制数字表示时间。此类系统的Unix时间戳最多可以使用到格林威治时间2038年01月19日03时14分07秒(二进制:01111111 11111111 11111111 11111111)。其后一秒,二进制数字会变为10000000 00000000 00000000 00000000,发生溢出错误,造成系统将时间误解为1901年12月13日20时45分52秒。这很可能会引起软件故障,甚至是系统瘫痪。使用64位二进制数字表示时间的系统(最多可以使用到格林威治时间292,277,026,596年12月04日15时30分08秒)则基本不会遇到这类溢出问题。

之前做了一个项目把时间戳转换为时间老是失败,上次在百度随便复制一个还是失败了,这篇文章主要是总结几个方法关于时间戳转化为时间的

一.js将时间转换成时间戳
1.js获取当前时间戳的方法

var timestamp1 = Date.parse(new Date());
var timestamp2 = (new Date()).valueOf();
var timestamp3 = new Date().getTime();
第一种:获取的时间戳是把毫秒改成000显示,第二种和第三种是获取了当前毫秒的时间戳。

2.js获取制定时间戳的方法

var oldTime = (new Date(“2015/06/23 08:00:20”)).getTime()/1000;
getTime()返回数值的单位是毫秒。
3.方法3

复制代码
function formatDate(now) {
var year=now.getFullYear();
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;
}
//如果记得时间戳是毫秒级的就需要*1000 不然就错了记得转换成整型
var d=new Date(1230999938);
alert(formatDate(d));

4.方法4

如果想弹出:2010-10-20 10:00:00这个格式的也好办

js需要把时间戳转为为普通格式,一般的情况下可能用不到的,

下面先来看第一种吧

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

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

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));

// 例子,比如需要这样的格式:yyyy-MM-dd hh:mm:ss
var date = new Date(1398250549490);
Y = date.getFullYear() + ‘-’;
M = (date.getMonth()+1 < 10 ? ‘0’+(date.getMonth()+1) : date.getMonth()+1) + ‘-’;
D = date.getDate() + ’ ';
h = date.getHours() + ‘:’;
m = date.getMinutes() + ‘:’;
s = date.getSeconds();
console.log(Y+M+D+h+m+s); //呀麻碟
//输出结果:2014-04-23 18:55:49
将日期格式转换成时间戳:
// 也很简单
date = new Date(‘2014-04-23 18:55:49:123’); //传入一个时间格式,如果不传入就是获取现在的时间了,就这么简单。
// 有三种方式获取
time1 = date.getTime()
time2 = date.valueOf()
time3 = Date.parse(date)

你可能感兴趣的:(js)