时间戳与时间之间的转换

Posted on 2016-08-18 14:24  听风吹来的种子  阅读(361)  评论(0编辑  收藏  举报
 1 // 获取当前时间戳(以s为单位)
 2 var timestamp = Date.parse(new Date());
 3 timestamp = timestamp / 1000;
 4 //当前时间戳为:1403149534
 5 console.log("当前时间戳为:" + timestamp);
 6 
 7 // 获取某个时间格式的时间戳
 8 var stringTime = "2016-08-18 14:05:12";
 9 var timestamp2 = Date.parse(new Date(stringTime));
10 timestamp2 = timestamp2 / 1000;
11 //2014-07-10 10:21:12的时间戳为:1404958872 
12 console.log(stringTime + "的时间戳为:" + timestamp2);
13 
14 // 将当前时间换成时间格式字符串
15 // var timestamp3 = 1403058804;//定时间
16 var timestamp3 = timestamp;//当前时间
17 var newDate = new Date();
18 newDate.setTime(timestamp3 * 1000);
19 // Wed Jun 18 2014 
20 console.log(newDate.toDateString());
21 // Wed, 18 Jun 2014 02:33:24 GMT 
22 console.log(newDate.toGMTString());
23 // 2014-06-18T02:33:24.000Z
24 console.log(newDate.toISOString());
25 // 2014-06-18T02:33:24.000Z 
26 console.log(newDate.toJSON());
27 // 2014年6月18日 
28 console.log(newDate.toLocaleDateString());
29 // 2014年6月18日 上午10:33:24 
30 console.log(newDate.toLocaleString());
31 // 上午10:33:24 
32 console.log(newDate.toLocaleTimeString());
33 // Wed Jun 18 2014 10:33:24 GMT+0800 (中国标准时间)
34 console.log(newDate.toString());
35 // 10:33:24 GMT+0800 (中国标准时间) 
36 console.log(newDate.toTimeString());
37 // Wed, 18 Jun 2014 02:33:24 GMT
38 console.log(newDate.toUTCString());
39 
40 Date.prototype.format = function(format) {
41 var date = {
42 "M+": this.getMonth() + 1,//
43 "d+": this.getDate(),//
44 "h+": this.getHours(),//
45 "m+": this.getMinutes(),//
46 "s+": this.getSeconds(),//
47 "q+": Math.floor((this.getMonth() + 3) / 3),//
48 "S+": this.getMilliseconds()//毫秒字段,以本地时间显示。返回值是 0 ~ 999 之间的一个整数
49 };
50 if (/(y+)/i.test(format)) {
51 format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
52 console.log('first:'+format);
53 }
54 for (var k in date) {
55 if (new RegExp("(" + k + ")").test(format)) {
56 format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
57 console.log('last:'+format);
58 }
59 }
60 return format;
61 }
62 console.log(newDate.format('yyyy-MM-dd h:m:s'));