js时间戳与日期格式之间相互转换

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

1. 将时间戳转换成日期格式

 1 // 简单的一句代码
 2 var date = new Date(时间戳); //获取一个时间对象
 3  
 4 /**
 5  1. 下面是获取时间日期的方法,需要什么样的格式自己拼接起来就好了
 6  2. 更多好用的方法可以在这查到 -> http://www.w3school.com.cn/jsref/jsref_obj_date.asp
 7  */
 8 date.getFullYear(); // 获取完整的年份(4位,1970)
 9 date.getMonth(); // 获取月份(0-11,0代表1月,用的时候记得加上1)
10 date.getDate(); // 获取日(1-31)
11 date.getTime(); // 获取时间(从1970.1.1开始的毫秒数)
12 date.getHours(); // 获取小时数(0-23)
13 date.getMinutes(); // 获取分钟数(0-59)
14 date.getSeconds(); // 获取秒数(0-59)
 1 // 比如需要这样的格式 yyyy-MM-dd hh:mm:ss
 2 var date = new Date(1398250549490);
 3 Y = date.getFullYear() + '-';
 4 M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
 5 D = date.getDate() + ' ';
 6 h = date.getHours() + ':';
 7 m = date.getMinutes() + ':';
 8 s = date.getSeconds(); 
 9 console.log(Y+M+D+h+m+s); //呀麻碟
10 // 输出结果:2014-04-23 18:55:49

2. 将日期格式转换成时间戳

 1 // 也很简单
 2 var strtime = '2014-04-23 18:55:49:123';
 3 var date = new Date(strtime); 
 4 //传入一个时间格式,如果不传入就是获取现在的时间了,这样做不兼容火狐。
 5 // 可以这样做
 6 var date = new Date(strtime.replace(/-/g, '/'));
 7  
 8 // 有三种方式获取,在后面会讲到三种方式的区别
 9 time1 = date.getTime();
10 time2 = date.valueOf();
11 time3 = Date.parse(date);
12  
13 /* 
14 三种获取的区别:
15 第一、第二种:会精确到毫秒
16 第三种:只能精确到秒,毫秒将用0来代替
17 比如上面代码输出的结果(一眼就能看出区别):
18 1398250549123
19 1398250549123
20 1398250549000 
21 */

3. Date()参数形式有7种

1 new Date("month dd,yyyy hh:mm:ss");
2 new Date("month dd,yyyy");
3 new Date("yyyy/MM/dd hh:mm:ss");
4 new Date("yyyy/MM/dd");
5 new Date(yyyy,mth,dd,hh,mm,ss);
6 new Date(yyyy,mth,dd);
7 new Date(ms);

比如:

1 new Date("September 16,2016 14:15:05");
2 new Date("September 16,2016");
3 new Date("2016/09/16 14:15:05");
4 new Date("2016/09/16");
5 new Date(2016,8,16,14,15,5); // 月份从0~11
6 new Date(2016,8,16);
7 new Date(1474006780);

猜你喜欢

转载自www.cnblogs.com/zhangchs/p/9231609.html