Date()对象的设置与解析

  • 怎么获取当前时间?
  • 怎么给Date对象设置特定时间?
  • 将Date对象解析为毫秒数?
  • 将Date对象解析为日月年?获取小时/分钟/秒?

  直接new Date()新建对象,可以获取当前时间的Date对象;另外还有 Date() 和 Date.now() 分别返回本地时间、1970年至今的毫秒数:

	/** 新建对象,默认就是当前时间 **/
	var time0 = new Date();
	console.log(time0); //  => Mon Dec 18 2017 00:14:05 GMT+0800 (中国标准时间)
	/** 打印出来是字符串,实际上是个对象 **/
	typeof time0 == "object";  // true
	time0.getTime()  // => 1513527245193 (此方法返回1970年1月1日至今的毫秒数)

	/** Date.now()返回的是个数字,不是Date对象 **/
	var time1 = Date.now();
	console.log(time1) //  => 1513525750309 (1970年1月1日至今的毫秒数)
	typeof time1 ==  "number"; // true
	time1.getTime(); // Error!

	/** Date()返回当前的本地时间,字符串 **/
	var time2 = Date();
	console.log(time2) //  => Mon Dec 18 2017 00:32:52 GMT+0800 (中国标准时间)
	typeof time2 ==  "string"; // true
	time2.getTime(); // Error!

  Date对象也是个构造函数,就像Number("5")==5一样,可以通过传参来设置值;也可以用Date.setTime()方法来设置值:

	/** 用毫秒数设置时间 **/
	var time3 = new Date(1513526617385)
	console.log(time3) // => Mon Dec 18 2017 00:03:37 GMT+0800 (中国标准时间)

	/** 用时间字符串设置时间 **/
	var time4 = new Date("Mon Dec 18 2017 00:09:00 GMT+0800 (中国标准时间)");
	console.log(time4) // => Mon Dec 18 2017 00:09:00 GMT+0800 (中国标准时间)
	var time5 = new Date("Sun, 17 Dec 2017 18:00:00 GMT");
	console.log(time5) // => Mon Dec 18 2017 02:00:00 GMT+0800 (中国标准时间)

	/** 用setTime()设置时间,只接收毫秒数 **/
	var time6 = new Date();
	time6.setTime(1513529227323);
	console.log(time6) // => Mon Dec 18 2017 00:47:07 GMT+0800 (中国标准时间)

  

  Date对象提供get系列方法和toSting系列方法,可以获取时间的number类型、string类型的数据:

        var time7 = new Date();

	/** getTime()返回毫秒数 **/
	time7.getTime()  // => 1513529665927

	/** toString系列方法返回字符串 **/
	// 返回本地时间
	time7.toString()  // => "Mon Dec 18 2017 00:54:25 GMT+0800 (中国标准时间)"
	// 返回世界时间
	time7.toUTCString()  // => "Sun, 17 Dec 2017 16:54:25 GMT"
	// 返回时间部分
	time7.toDateString()  // => "00:54:25 GMT+0800 (中国标准时间)"

	/** 使用get系列方法获取具体某一项的值(数字类型) **/
	time7.getFullYear()  // => 2017
	time7.getMonth()  // => 11(0-11,比实际月份少1)
	time7.getDate()  // => 18
	time7.getHours()  // => 0
	time7.getMinutes()  // => 54
	time7.getSeconds()  // => 25    
原文地址:https://www.cnblogs.com/yangshifu/p/8054293.html