【原生JS】时间 Date API

日期常用API

复制代码
getTime();//毫秒数
getFullYear();//年
getMonth();//月 (0~11)要+1
getDate();//日
getHours();//小时
getMinutes();//分钟
getSeconds();//秒

Date.now();//当前时间毫秒数
new Date();//当前时间

1、当前时间换时间戳
var timestamp = parseInt(new Date().getTime()/1000); // 当前时间戳
document.write(timestamp);

2、当前时间换日期字符串
var now = new Date();
var yy = now.getFullYear(); //年
var mm = now.getMonth() + 1; //月
var dd = now.getDate(); //日
var hh = now.getHours(); //时
var ii = now.getMinutes(); //分
var ss = now.getSeconds(); //秒
var clock = yy + “-”;
if(mm < 10) clock += “0”;
clock += mm + “-”;
if(dd < 10) clock += “0”;
clock += dd + " ";
if(hh < 10) clock += “0”;
clock += hh + “:”;
if (ii < 10) clock += ‘0‘;
clock += ii + “:”;
if (ss < 10) clock += ‘0‘;
clock += ss;
document.write(clock); //获取当前日期

3、日期字符串转时间戳
var date = ‘2015-03-05 17:59:00.0‘;
date = date.substring(0,19);
date = date.replace(/-/g,‘/‘);
var timestamp = new Date(date).getTime();
document.write(timestamp);

4、时间戳转日期字符串
var timestamp = ‘1425553097‘;
var d = new Date(timestamp * 1000); //根据时间戳生成的时间对象
var date = (d.getFullYear()) + “-” +
(d.getMonth() + 1) + “-” +
(d.getDate()) + " " +
(d.getHours()) + “:” +
(d.getMinutes()) + “:” +
(d.getSeconds());
document.write(date);

获取JavaScript 的时间使用内置的Date函数完成
var mydate = new Date();
mydate.getYear(); //获取当前年份(2位)
mydate.getFullYear(); //获取完整的年份(4位,1970-???)
mydate.getMonth(); //获取当前月份(0-11,0代表1月)
mydate.getDate(); //获取当前日(1-31)
mydate.getDay(); //获取当前星期X(0-6,0代表星期天)
mydate.getTime(); //获取当前时间(从1970.1.1开始的毫秒数)
mydate.getHours(); //获取当前小时数(0-23)
mydate.getMinutes(); //获取当前分钟数(0-59)
mydate.getSeconds(); //获取当前秒数(0-59)
mydate.getMilliseconds(); //获取当前毫秒数(0-999)
mydate.toLocaleDateString(); //获取当前日期
var mytime=mydate.toLocaleTimeString(); //获取当前时间
mydate.toLocaleString( ); //获取日期与时间

日期时间脚本库方法列表

Date.prototype.isLeapYear 判断闰年
Date.prototype.Format 日期格式化
Date.prototype.DateAdd 日期计算
Date.prototype.DateDiff 比较日期差
Date.prototype.toString 日期转字符串
Date.prototype.toArray 日期分割为数组
Date.prototype.DatePart 取日期的部分信息
Date.prototype.MaxDayOfDate 取日期所在月的最大天数
Date.prototype.WeekNumOfYear 判断日期所在年的第几周
StringToDate 字符串转日期型
IsValidDate 验证日期有效性
CheckDateTime 完整日期时间检查
daysBetween 日期天数差

在这里插入图片描述

设置时间值
setFullYear: 设置年份
setMonth:设置月份
setDate:设置每月的某一天
setHours:设置时
setNubytes:设置分
setSeconds:设置秒
setMilliseconds:设置毫秒

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值