你的位置:首页 > Java教程

[Java教程]为 Date 对象添加 ago 属性


/** 此处,__defineGetter__与__defineSetter__相当于C#实体中类中的get与set**/Date.prototype.__defineGetter__('ago',function () {    var diff = ((new Date()).getTime() - this.getTime()) / 1000,      day_diff = Math.floor(diff / 86400);    return day_diff == 0 &&            diff < 60 && 'just now' ||            diff < 120 && '1 minute ago' ||            diff < 3600 && Math.floor( diff / 60 ) + 'minutes ago' ||            diff < 7200 && '1 hour ago' ||            day_diff == 1 && 'yesterday' ||            day_diff < 7 && day_diff + 'days ago' ||            Math.ceil( day_diff / 7 ) + 'weeks ago';  });

测试一下

var a = new Date('12/12/1990')a.ago// "1353weeks ago"var a = new Date('2016-11-9')a.ago// "yesterday"var a = new Date('2016-11-5')a.ago// "5days ago"

今后就根据需求变动其return的条件即可