这篇文章主要介绍了js实现时间显示几天前、几小时前或者几分钟前的方法,实例汇总分析了时间显示格式转换的常用思路与技巧,需要的朋友可以参考下
这里汇总了js实现时间显示几天前、几小时前或者几分钟前的常见方法。分享给大家供大家参考。具体如下:
方法一:
个人做法是保存时间戳,然后在前端用jq插件做转换,比如 smart-time-ago
方法二:
(通过freemarker模板)如果用freemarker模板可以这样写,别的模板类推
根据自己的意愿修改条件和输出,把你的datetime传进去即可
?
1 2 3 4 5 6 7 8 9 10 11 12 <#macro timeline_dt datetime=.now> <#assign ct = (.now?long-datetime?long)/1000> <#if ct gte 31104000><#--n年前-->${(ct/31104000)?int}年前 <#t><#elseif ct gte 2592000><#--n月前-->${(ct/2592000)?int}个月前 <#t><#elseif ct gte 86400*2><#--n天前-->${(ct/86400)?int}天前 <#t><#elseif ct gte 86400><#--1天前-->昨天 <#t><#elseif ct gte 3600><#--n小时前-->${(ct/3600)?int}小时前 <#t><#elseif ct gte 60><#--n分钟前-->${(ct/60)?int}分钟前 <#t><#elseif ct gt 0><#--n秒前-->${ct?int}秒前 <#t><#else>刚刚 </#if> </#macro>方法三:
找到一个专门的插件PrettyTime
?
1 2 3 4 public static void main(String[] args) { PrettyTime p = new PrettyTime(); System.out.println(p.format(DateUtils.addDays(new Date(), 2))); }方法四:
自定义Java方法:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 private final static long minute = 60 * 1000;// 1分钟 private final static long hour = 60 * minute;// 1小时 private final static long day = 24 * hour;// 1天 private final static long month = 31 * day;// 月 private final static long year = 12 * month;// 年 /** * 返回文字描述的日期 * * @param date * @return */ public static String getTimeFormatText(Date date) { if (date == null) { return null; } long diff = new Date().getTime() - date.getTime(); long r = 0; if (diff > year) { r = (diff / year); return r + "年前"; } if (diff > month) { r = (diff / month); return r + "个月前"; } if (diff > day) { r = (diff / day); return r + "天前"; } if (diff > hour) { r = (diff / hour); return r + "个小时前"; } if (diff > minute) { r = (diff / minute); return r + "分钟前"; } return "刚刚"; }方法五:
使用js插件:(原版的timeago.js)
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 // Smart Time Ago v0.1.0 // Copyright 2012, Terry Tai, Pragmatic.ly // https://pragmatic.ly/ // Licensed under the MIT license. // https://github.com/pragmaticly/smart-time-ago/blob/master/LICENSE (function() { var TimeAgo; TimeAgo = (function() { function TimeAgo(element, options) { this.startInterval = 60000; this.init(element, options); } TimeAgo.prototype.init = function(element, options) { this.$element = $(element); this.options = $.extend({}, $.fn.timeago.defaults, options); this.updateTime(); return this.startTimer(); }; TimeAgo.prototype.startTimer = function() { var self;