js常用的时间函数案例整理

var now=new Date();
console.log(now);
// Sun Apr 08 2018 14:38:48 GMT+0800 (中国标准时间)
console.log(now.getDate());
// 当前日 8
console.log(now.getMonth()+1);
//当前月  4
console.log(now.getFullYear());
//当前年  2018
console.log(now.getTime());
//当前时间戳(1970年到现在)  1523169789892
console.log(Date.parse("2018 05 12"));
console.log(Date.parse("05 12 2018"));
console.log(Date.parse("May 12,2018"));
console.log(Date.parse("2018,05,12"));
console.log(Date.parse("2018/05/12"));
//1970/01/01-2018/05/12的毫秒数 1526054400000
console.log(now.valueOf());
//返回当前时间的原始值,相当于上边的时间戳  1523169789892
var now=new Date();console.log(now.setDate(1));
//设置时间为本月的第一天,返回时间戳
//同样可以设置月,年等
console.log()
Date的构造函数
var date=new Date();
var date=new Date(string);//参照上边的时间戳格式
var date=new Date(year,month-1,day,hours,minutes,seconds);
var date=new Date(时间戳);


相关方法整理
//将date转换为特定的时间格式,可拓展
function dateToString(date, format) {
var yearstr = date.getFullYear();
var imonth = date.getMonth() + 1;
var monthstr = imonth + "";
if (imonth < 10) {
monthstr = "0" + monthstr;
}
var daystr = date.getDate();
if (daystr < 10) {
daystr = "0" + daystr;
}
if (format == "yyyymm") {
return yearstr + "年" + monthstr + "月";
}
else if (format == "yyyyss") {
return yearstr + "年" + parseInt(imonth / 3 + 1) + "季度";
}
else if (format == "yyyy") {
return yearstr + "年";
}
else if (format == "yyyyhh") {
return yearstr + "年" + (imonth > 6 ? "下半年" : "上半年");
}
else if (format == "yyyyww") {
var week = getWeek(date);
if (week < 10) {
week = "0" + week;
}
return yearstr + "年" + week + "周";
}
else {
return yearstr + "年" + monthstr + "月" + daystr + "日";
}
}
时间字符串转换
var dateStr="2015-12-15";
console.log(dateStr.replace(/-/g,"/"));//  2015/12/15
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值