js-日期对象

Date是一个构造函数需要创建date实例使用相关方法

Date 实例用来处理日期和时间

创建date实例

/* 构造函数的方式 */
  // let date = new Date()
  // new Date() //实例化的一个日期对象 // Wed Aug 23 2023 10:36:49 GMT+0800 (中国标准时间)

  /* 通过这种方式 可以打印出 过去的时间 */
  // 9 1,2017,14:58:12 月 日 年 时 分 秒/
  // var tdate = new Date("9 1,2017,14:58:12")
  // console.log(tdate) 
  // var tdate = new Date('2019-10-30 13:20:22')
  // console.log(tdate)

  /* 上面使用一个字符串参数传过去的 */
  /* 在上面的用字符串表示的月份中 9 就代表9月 10 就代表10月 */

  /* 用数字类型参数,和逗号分割传参: 是从0开始算的,这里8 就代表9月 */
  /* 这下面是用 6个参数 分别传过去的,所以和上面的传入的方式不一样
  产生的结果也不一样*/
  // var tdate = new Date(2018, 8, 1, 13, 22, 23)
  // console.log(tdate)

date对象方法

// var date = new Date()
// 日期对象格式化
  /* 返回 Date 对象的号数,其值介于1~31之间 */
  /* 获取日期 */
  // console.log(date.getDate());

  /* 返回 Date 对象的星期中的每一天,其值介于0~6之间(注:0代表周日)*/
  /* 1代表周一 0为周天*/
  /* 获取星期几 */
  /* console.log( date.getDay() ); */

  /* 返回 Date 对象的小时数,其值介于0~23之间 */
  /* 24点就是0点 */
  /* console.log( date.getHours() ); */

  /* 返回 Date 对象的分钟数,其值介于0~59之间 */
  /* 60分就是0 */
  /* console.log( date.getMinutes() ); */

  /* 返回 Date 对象的秒数,其值介于0~59之间 */
  /* 60秒就是0 */
  /* console.log( date.getSeconds() ); */

  /*★特殊 返回 Date 对象的月份,其值介于0~11之间(注:0代表1月份)分|秒|星|星期几返回的0都为最大值(60s = 0 60min = 0 星期天 = 0)*/
  /* console.log( date.getMonth() ); */

  /* 返回 Date 对象的年份,其值为4位数 */
  /*  console.log( date.getFullYear() ); */


// 获取日期的总的毫秒形式
    //Date 对象是基于1970年1月1日(世界标准时间)起的毫秒数
var now = new Date()
// 1. 用于获取对象的原始值的毫秒数
console.log(now.valueOf())
console.log(now.getTime())
// 2. 简单写可以这么做
var A = + new Date()
// 3. HTML5中提供的方法,有兼容性问题
var now = Date.now()

练习

倒计时

// overTime 终点时间
  function djs (overTime) {
    let overTimeMilliseconds = + new Date(overTime)
    let nowMilliseconds = + new Date()
    // 计算出剩余时间秒数
    let remainder = (overTimeMilliseconds - nowMilliseconds) / 1000
    let rD = parseInt(remainder / 60 / 60 / 24)
    let rH = parseInt(remainder / 60 / 60) < 9 ? `0${parseInt(remainder / 60 / 60)}` : parseInt(remainder / 60 / 60)
    let rM = parseInt(remainder % 60) < 9 ? `0${parseInt(remainder % 60)}` : parseInt(remainder % 60)
    let rS = parseInt(remainder % 60) < 9 ? `0${parseInt(remainder % 60)}` : parseInt(remainder % 60)
    console.log(`${rD}天:${rH}时:${rM}分${rS}秒`)
  }

  djs('2023-8-24 18:00:00')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值