js Date方法 设置和获取时间

时间对象

使用new Date获取一个时间对象:var date = new Date()

  • date,(中国标准时间)
  • date.toUTCString(),获取格林尼治日期时间
  • date.toLocaleString(),获取本地日期时间
  • date.toLocaleDateString(),获取本地日期
  • date.toLocaleTimeString(),获取本地时间
var date=new Date();
//当前时间为2020年1月1日 22:12:29
console.log(date);
//Wed Jan 01 2020 22:12:29 GMT+0800 (中国标准时间)
console.log(date.toUTCString());
//Wed, 01 Jan 2020 14:12:29 GMT
console.log(date.toLocaleString());
//2020/1/1 下午10:12:29
console.log(date.toLocaleDateString());
//2020/1/1
console.log(date.toLocaleTimeString());
//下午10:12:29

时间的获取方法

  • Date(),返回当日的日期和时间。
  • getDate(),返回几号 (1 ~ 31)。
  • getDay(),返回星期几 (0 ~ 6),星期日为0。
  • getMonth(),返回月份 (0 ~ 11),从0开始。
  • getFullYear(),返回四位数字的年份。
  • getYear(),两位数的年份,从1900年开始。
  • getHours(),返回小时 (0 ~ 23)。
  • getMinutes(),返回分钟 (0 ~ 59)。
  • getSeconds(),返回秒 (0 ~ 59)。
  • getMilliseconds(),返回毫秒(0 ~ 999)。
  • getTime(),返回 1970 年 1 月 1 日至今的毫秒数。
var date=new Date();
//当前时间为2020年1月1日 22:12:29
console.log(date.getYear());//120
console.log(date.getFullYear());//2020
console.log(date.getMonth());//0
console.log(date.getDate());//1
console.log(date.getDay());//3
console.log(date.getHours());//22
console.log(date.getMinutes());//12
console.log(date.getSeconds());//29
console.log(date.getMilliseconds());//0
console.log(date.getTime());//1577887949000
console.log(date.getUTCDate());//1

时间的设置方法

  • setDate(),设置几号 (1 ~ 31)。
  • setMonth(),设置月份 (0 ~ 11)。
  • setFullYear(),设置年份(四位数字)。
  • setHours(),设置小时 (0 ~ 23)。
  • setMinutes(),设置分钟 (0 ~ 59)。
  • setSeconds(),设置秒 (0 ~ 59)。
  • setMilliseconds(),设置毫秒 (0 ~ 999)。
  • setTime(),以毫秒设置 Date 对象。

设置日期时间时,如果超出范围,就会自动进位

var date=new Date();
date.setFullYear(2021);
// 设置日期时间时,如果超出范围,就会自动进位
date.setMonth(12);
console.log(date);

date.setMinutes(date.getMinutes()+5);
console.log(date);

也可以在创建date的时候,传入要设置的时间参数

参数形式有以下5种:

  1. new Date(“month dd,yyyy hh:mm:ss”);
  2. new Date(“month dd,yyyy”);
  3. new Date(yyyy,mth,dd,hh,mm,ss);
  4. new Date(yyyy,mth,dd);
  5. new Date(ms);

参数意义:

  • month:用英文 表示月份名称,从January到December
  • mth:用整数表示月份,从0(1月)到11(12月)
  • dd:表示一个 月中的第几天,从1到31
  • yyyy:四位数表示的年份
  • hh:小时数,从0(午夜)到23(晚11点)
  • mm: 分钟数,从0到59的整数
  • ss:秒数,从0到59的整数
  • ms:毫秒数,为大于等于0的整数

注意参数的格式,第3、4、5种一定要是整型的才可以,不能是字符串

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

//下面的各种创建形式都表示2006年1月12日这一天。
new Date("January 12,2006 22:19:35"); 
new Date("January 12,2006"); 
new Date(2006,0,12,22,19,35); 
new Date(2006,0,12); 
new Date(1137075575000); 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值