时间

// 对Date的扩展,将 Date 转化为指定格式的String

// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,

// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)

// 例子:

// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423

// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18

Date.prototype.Format = function (fmt) { //author: meizz

var o = {

"M+": this.getMonth() + 1, //月份

"d+": this.getDate(), //日

"h+": this.getHours(), //小时

"m+": this.getMinutes(), //分

"s+": this.getSeconds(), //秒

"q+": Math.floor((this.getMonth() + 3) / 3), //季度

"S": this.getMilliseconds() //毫秒

};

if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.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;

}调用: var time1 = new Date().Format("yyyy-MM-dd");var time2 = new Date().Format("yyyy-MM-dd HH:mm:ss");


js获取当前时间前后N天前后日期的方法

functionGetDateStr(AddDayCount) {

vardd =newDate();

dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期

vary = dd.getFullYear();

varm = (dd.getMonth()+1)<10?"0"+(dd.getMonth()+1):(dd.getMonth()+1);//获取当前月份的日期,不足10补0

vard = dd.getDate()<10?"0"+dd.getDate():dd.getDate();//获取当前几号,不足10补0

returny+"-"+m+"-"+d;

}

console.log("半年前:"+GetDateStr(-180));

console.log("三月前:"+GetDateStr(-90));

console.log("一月前:"+GetDateStr(-30));

console.log("昨天:"+GetDateStr(-1));

console.log("今天:"+GetDateStr(0));

console.log("明天:"+GetDateStr(1));

console.log("后天:"+GetDateStr(2));

console.log("一月后:"+GetDateStr(30));

console.log("三月后:"+GetDateStr(90));

console.log("半年后:"+GetDateStr(180));

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • js获取日期:前天、昨天、今天、明天、后天 /** *ldq2017年11月14日16:12:06 * 获取当前时...
    空白_阅读 1,836评论 0 0
  • [Js获取当前日期时间及其它操作] 日期时间脚本库方法列表 js代码://--------------------...
    JS_swh阅读 485评论 0 3
  • // 获取当前时间戳(以s为单位)var timestamp = Date.parse(new Date());t...
    箱猫日和阅读 496评论 0 1
  • 在React下面,时间戳和时间字符串的转换的方法中的getYear()等方法失灵,可采取这种转换方式。要改格式的话...
    迷糊的呆呆阅读 10,397评论 0 1
  • 当我的家庭还可以算上是资本家的年代,长辈们对我的教育投资是不遗余力的,但是他们并没有懂得繁华不可久恃的道理,毅然将...
    卫陈阅读 704评论 3 0