Date对象及Sting对象1

121 阅读2分钟

Date对象

  • 通过构造Date函数可以定义一个时间对象

  • new Date中的参数是一个字符串

  • 参数格式有很多种但必须是字符串类型

  • 如果传递的是数字类型使用逗号分隔的

  • 月份是从0开始的 0 表示1月 1表示2月

  • 如果new Date中不添加任何参数 则返回当前的日期和时间

      let date = new Date();
      let tDate = new Date('2021-09-10 11:11:11');
      let oDate = new Date(2021,10,30,10,10,10)
      console.log (date)
      console.log (tDate)
      console.log (oDate)
      
    

Date的常用方法

    // let date = new Date('2020-1-11 11:11:11')
    // getFullYear 返回对象的年份,其值为四位数
    // document.write(date.getMonth() )

    // getMonth()返回对象的月份,其值介于0~11之间(0代表1月份)
    // document.write(date.getMonth() )

    // getDate() 返回对象的一个月中的一天,其值介于131之间
    // document.write(date.getDate() );

    // getDay() 返回对象在一个星期中的一天 值为0~6之间
    // document.write(date.getDay() );

    // getHours() 返回对象的小时数 值为0~23之间
    // document.write(dategetHours() );

    // getMinutes() 返回对象的分钟数,值为0~59之间
    // document.write(date.getMinutes())

    // getSeconds() 返回对象的秒数,值为 0~59之间
    // document.write(date.getSeconds());
    

时间戳

getTime 返回1970-1-1 到现在的毫秒数

构造函数本身有一个now方法,执行后可以获取到1970年1月1日到现在的毫秒数,但是不能获取到1970年1月1日到指定时间的毫秒数

let date =  new Date();
document.write('1970年1月1日到现在的毫秒数:'+ date.getTime);
document.write('1970年1月1日到现在的毫秒数:'+ Date.now());

String对象

定义方法

  • 通过构造String函数来定义可以将数组转化为字符串

  • 通过字面量来定义

      let str = new String('hello world');
      let str1 = 'hello world';
    

字符串的属性

length 返回字符串的长度

let str = 'hello'
console.log( str.length);

字符串的使用方法

charAt 返回指定位置的字符(字符串中第一个字符的下标是0)

let str = 'hello world';
let v = str.charAt(1)
document.write(v);

indexOf

  • 返回指定的字符串值在字符串中首次出现的位置
  • 只能返回首次出现的字符位置
  • 如果没有则返回-1 let str = 'hello world'; let index = str.indexOf('l')