JS学习笔记

详解JS数据类型/转换/方法(Date)

2018-06-15  本文已影响0人  XKolento

js的数据类型

1.Number
2.String
3.Boolean
4.Symbol (es2015新增)
5.Object (Function,Arr,Date,RegExp)
6.Null
7.Undefined
另外则还有一些内置的Err对象。

1.Date 对象

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

var myDate=new Date()
//Date 对象会自动把当前日期和时间保存为其初始值。
//Fri Jun 15 2018 13:38:29 GMT+0800 (中国标准时间)

2.Date 常用对象方法

Date()
返回当前时间
new Date()与Date()的区别

var d1=Date();        //返回一个字符串(string),没有getDate等日期对象方法,内容为当前时间
var d2=new Date();    //返回一日期对象,可以调用getDate(),内容为当前时间

getDate()
从 Date 对象返回一个月中的某一天 (1 ~ 31)。

new Date().getDate() //15 返回当前日期

getDay()
返回一周中的某一天,0~6,0代表周日,1代表周一

new Date().getDay() //5 返回当前星期
weekday[0]="Sunday"
weekday[1]="Monday"
weekday[2]="Tuesday"
weekday[3]="Wednesday"
weekday[4]="Thursday"
weekday[5]="Friday"
weekday[6]="Saturday"

getMonth()
从 Date 对象返回月份 (0 ~ 11)。0代表1月

new Date().getMonth() //5 返回当前日期

getFullYear()
从 Date 对象以四位数字返回年份。

new Date().getFullYear() // 2018

getHours()
返回 Date 对象的小时 (0 ~ 23)。

new Date().getHours() // 14   14点

其他类似方法如下:
getMinutes():返回 Date 对象的分钟 (0 ~ 59)。
getSeconds():返回 Date 对象的秒数 (0 ~ 59)。
getMilliseconds():返回 Date 对象的毫秒(0 ~ 999)。
getTime()(时间戳)
返回 1970 年 1 月 1 日至今的毫秒数。

new Date().getTime()

getUTCDate()
据世界时从 Date 对象返回月中的一天 (1 ~ 31)。
与getDate()的区别:一个返回的是本地时间,一个返回的是世界时间(格林威治时间),
格林威治时间比东八区本地时间慢8小时。

其他类似方法:
getUTCDay():根据世界时从 Date 对象返回周中的一天 (0 ~ 6)。
getUTCMonth():根据世界时从 Date 对象返回月份 (0 ~ 11)。
getUTCFullYear():根据世界时从 Date 对象返回四位数的年份。
getUTCHours():根据世界时返回 Date 对象的小时 (0 ~ 23)。
getUTCMinutes():根据世界时返回 Date 对象的分钟 (0 ~ 59)。
getUTCSeconds():根据世界时返回 Date 对象的秒钟 (0 ~ 59)。
getUTCMilliseconds():根据世界时返回 Date 对象的毫秒(0 ~ 999)。

setDate()
设置 Date 对象中月的某一天 (1 ~ 31)。

var d = new Date()
d.setDate(1)
document.write(d) //Fri Jun 01 2018 14:44:53 GMT+0800 (中国标准时间)

其他类似方法:
setMonth():设置 Date 对象中月份 (0 ~ 11)。
setFullYear():设置 Date 对象中的年份(四位数字)。
setHours():设置 Date 对象中的小时 (0 ~ 23)。
setMinutes():设置 Date 对象中的分钟 (0 ~ 59)。
setSeconds():设置 Date 对象中的秒钟 (0 ~ 59)。
setMilliseconds():设置 Date 对象中的毫秒 (0 ~ 999)。
setTime():以毫秒设置 Date 对象。
还有对应的 UTC 系列

var d = new Date()
d.setTime(15642111552166)
document.write(d)  //Sat Sep 05 2465 06:59:12 GMT+0800 (中国标准时间)

⑩ 转化时间的几种方法与之间的区别

toString() 方法可把 Date 对象转换为字符串,并返回结果,使用本地时间表示。
var d = new Date()
document.write (d.toString()) //Fri Jun 15 2018 14:51:29 GMT+0800 (中国标准时间)
toTimeString() 方法可把 Date 对象的时间部分转换为字符串,并返回结果。
new Date().toTimeString() //14:53:53 GMT+0800 (中国标准时间)
toDateString() 方法可把 Date 对象的日期部分转换为字符串,并返回结果。
new Date().toDateString()  //Fri Jun 15 2018
toLocaleString() 根据本地时间格式,把 Date 对象转换为字符串。
new Date().toLocaleString()  //2018/6/15 下午2:56:56
上一篇 下一篇

猜你喜欢

热点阅读