Date、定时器、JSON

147 阅读1分钟

Date

Date是一个构造函数,可以构造出一个时间对象

//📅 2023/07/25/ 14:21:00 星期二
var date = new Date() //用Date构造函数创建date对象
date //展示当前日期 Tue Jul 25 2023 14:21:00 GMT+0800 (中国标准时间)
//get
date.getDate() //日 25
date.getDay() //星期几 2
date.getMonth() //月,从0开始 6
date.getFullYear() //年 2023
date.getHours() //14
date.getMinutes() //21
date.getSeconds() //00
date.getTime() //返回1970年1月1日至今的毫秒数,时间戳 ⏳
//set
date.setDate(12) //返回set后的时间戳,并改变原来的值
date.setDay()
date.setMonth()
date.setTime()
//to
date.toString()
date.toTimeString()

定时器

window上的方法


//interval
setInterval(function(){
    console.log(Date())
},1000) //每隔1000毫秒打印一次

const timer = setInterval(function(){},500) //会返回一个唯一标识
clearInterval(timer) //清除interval定时器

//timeout
var timeout = setTimeout(function(){
    
},1000)//1000毫秒后再执行里面的代码
clearTimeout(timeout) //清除timeout定时器

JSON

是js内置全局对象,不是构造函数

const obj = {
    name : 'hay',
    color : 'blue'
}
JSON.stringify(obj) //把对象转换成json格式
//'{"name":"hay","color":"blue"}'

const str = '{"name":"hay","color":"blue"}'
JSON.parse(str) //把字符串解析成对象
//{name: 'hay', color: 'blue'}