js实现日期格式化以及获取一周前格式化后的日期

直接上代码,如下:

function dateFormat(Date,fmt) {
  var o = {
      "M+": Date.getMonth() + 1, //月份 
      "d+": Date.getDate(), //日 
      "H+": Date.getHours(), //小时 
      "m+": Date.getMinutes(), //分 
      "s+": Date.getSeconds(), //秒 
      "q+": Math.floor((Date.getMonth() + 3) / 3), //季度 
      "S": Date.getMilliseconds() //毫秒 
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (Date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
  if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
};

let startDate = new Date();
startDate.setTime(myDate.getTime() - 3600 * 1000 * 24 * 7); //获取一周前的Date对象

let startTime = dateFormat(startDate,'yyyy-MM-dd HH:mm:ss'); //获取一周前的格式化后日期
console.log("一周前日期 = "+startTime);//2018-09-03 17:18:29

let endTime = dateFormat(new Date(),'yyyy-MM-dd HH:mm:ss');  //获取当前格式化后日期 
console.log("当前日期 = "+endTime); //2018-09-10 17:18:29

// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 20018-09-10 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 20018-09-10 8:9:4.18 

日期格式化函数dateFormat(Date,fmt);

参数说明:Date为new Date()出的日期实例;fmt为所需要的日期格式,如“yyyy-MM-dd hh:mm:ss.S”、“yyyy-M-d h:m:s.S”、“yyyy-MM-dd HH:mm:ss”

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
获取本周当日和本月时间的方法同上一个回答一致,只是在格式化时间上有所不同。可以使用 JavaScript 中的 Date 对象的一些方法来进行格式化。 以下是获取本周当日和本月时间并格式化的示例代码: ```javascript // 格式化日期 function formatDate(date) { let year = date.getFullYear(); let month = date.getMonth() + 1; let day = date.getDate(); month = month < 10 ? '0' + month : month; day = day < 10 ? '0' + day : day; return year + '-' + month + '-' + day; } // 获取本周的第一天和最后一天 let now = new Date(); let dayOfWeek = now.getDay(); let today = now.getDate(); let startDay = new Date(now.getFullYear(), now.getMonth(), today - dayOfWeek); let endDay = new Date(now.getFullYear(), now.getMonth(), today + (6 - dayOfWeek)); console.log(formatDate(startDay)); // 格式化后的本周第一天 console.log(formatDate(endDay)); // 格式化后的本周最后一天 // 获取本月的第一天和最后一天 let year = now.getFullYear(); let month = now.getMonth() + 1; let startMonth = new Date(year, month - 1, 1); let endMonth = new Date(year, month, 0); console.log(formatDate(startMonth)); // 格式化后的本月第一天 console.log(formatDate(endMonth)); // 格式化后的本月最后一天 ``` 以上代码中,我们定义了一个 formatDate 函数来格式化日期,然后使用该函数对获取到的时间进行格式化输出。需要注意的是,在格式化月份和日期时,需要判断是否小于 10,如果小于 10 则在面加上一个 0。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

麦兜_冰夕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值