JS中Date对象用法

一:Date对象是什么

Date 对象用于处理日期和时间。

二:Date创建语法

1. 直接获取当前时间为标准时间

  var date = new Date()  

  console.log(date)  //Tue Dec 12 2017 23:09:42 GMT+0800 (中国标准时间)

  注释:Date 对象会自动把当前日期和时间保存为其初始值。

2. 指定时间转变成标准时间

  var date1 = new Date("January 12,2006 22:19:35")

  console.log(date1)  //Thu Jan 12 2006 22:19:35 GMT+0800 (中国标准时间)

  其下面几种格式都可以:

  // new Date("month dd,yyyy hh:mm:ss");
  // new Date("month dd,yyyy");
  // new Date(yyyy,mth,dd,hh,mm,ss);
  // new Date(yyyy,mth,dd);
  // new Date(ms);

三:常用的对象方法

  date.getFullYear()  //2017  从 Date 对象以四位数字返回年份

  date.getMonth()  //11  从 Date 对象返回月份 (0 ~ 11)

  date.getDay()  //2  从 Date 对象返回一周中的某一天 (0 ~ 6)

  date.getDate()  //12  从 Date 对象返回一个月中的某一天 (1 ~ 31)

  date.getHours()  //23  返回 Date 对象的小时 (0 ~ 23)

  date.getMinutes()  //30  返回 Date 对象的分钟 (0 ~ 59)

  date.getSeconds()  //54  返回 Date 对象的秒数 (0 ~ 59)

  date.getMilliseconds()  返回 Date 对象的毫秒(0 ~ 999)

  date.getTime()  返回 1970 年 1 月 1 日至今的毫秒数

四:各案例转换

1.  var time = “2017-12-12”转换成毫秒时间戳

  new Date( time.replace(/-/g,"/") ).getTime()   //1513008000000

 

2. var time = 1513008000000转换成“2017-12-12”

 注意:time不能是string要是number

  var date = new Date(time)

  var year1 = date2.getFullYear()
  var month = date2.getMonth()
  var today = date2.getDate()
  var Time1 = year1 + "-" + month + "-" + today

posted @ 2017-12-13 00:03  逆向鹦鹉螺  阅读(9502)  评论(0编辑  收藏  举报