评论时间戳格式化

如图:

 

注意,评论时间戳的格式,刚才,几小时之前,几天之前.....

 

实现需要一个时间格式的工具类,如果用java.util.Date当然也可以实现,这里说的是更方便的joda-time。

maven地址:http://search.maven.org/#search%7Cga%7C1%7Cjoda-time

 

工具类如下:

package com.chunsheng.me.timestamp;import java.util.Date;
import java.util.concurrent.TimeUnit;import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Hours;
import org.joda.time.Minutes;
import org.joda.time.Months;
import org.joda.time.Weeks;
import org.joda.time.Years;class TimeStampFormatter {/*** For use with java.util.Date*/public String format(Date timestamp) {long millisFromNow = getMillisFromNow(timestamp);long minutesFromNow = TimeUnit.MILLISECONDS.toMinutes(millisFromNow);if (minutesFromNow < 1) {return "just now";}long hoursFromNow = TimeUnit.MILLISECONDS.toHours(millisFromNow);if (hoursFromNow < 1) {return formatMinutes(minutesFromNow);}long daysFromNow = TimeUnit.MILLISECONDS.toDays(millisFromNow);if (daysFromNow < 1) {return formatHours(hoursFromNow);}long weeksFromNow = TimeUnit.MILLISECONDS.toDays(millisFromNow) / 7;if (weeksFromNow < 1) {return formatDays(daysFromNow);}long monthsFromNow = TimeUnit.MILLISECONDS.toDays(millisFromNow) / 30;if (monthsFromNow < 1) {return formatWeeks(weeksFromNow);}long yearsFromNow = TimeUnit.MILLISECONDS.toDays(millisFromNow) / 365;if (yearsFromNow < 1) {return formatMonths(monthsFromNow);}return formatYears(yearsFromNow);}private long getMillisFromNow(Date commentedAt) {long commentedAtMillis = commentedAt.getTime();long nowMillis = System.currentTimeMillis();return nowMillis - commentedAtMillis;}/*** For use with org.joda.DateTime*/public String format(DateTime commentedAt) {DateTime now = DateTime.now();Minutes minutesBetween = Minutes.minutesBetween(commentedAt, now);if (minutesBetween.isLessThan(Minutes.ONE)) {return "just now";}Hours hoursBetween = Hours.hoursBetween(commentedAt, now);if (hoursBetween.isLessThan(Hours.ONE)) {return formatMinutes(minutesBetween.getMinutes());}Days daysBetween = Days.daysBetween(commentedAt, now);if (daysBetween.isLessThan(Days.ONE)) {return formatHours(hoursBetween.getHours());}Weeks weeksBetween = Weeks.weeksBetween(commentedAt, now);if (weeksBetween.isLessThan(Weeks.ONE)) {return formatDays(daysBetween.getDays());}Months monthsBetween = Months.monthsBetween(commentedAt, now);if (monthsBetween.isLessThan(Months.ONE)) {return formatWeeks(weeksBetween.getWeeks());}Years yearsBetween = Years.yearsBetween(commentedAt, now);if (yearsBetween.isLessThan(Years.ONE)) {return formatMonths(monthsBetween.getMonths());}return formatYears(yearsBetween.getYears());}private String formatMinutes(long minutes) {return format(minutes, " minute ago", " minutes ago");}private String formatHours(long hours) {return format(hours, " hour ago", " hours ago");}private String formatDays(long days) {return format(days, " day ago", " days ago");}private String formatWeeks(long weeks) {return format(weeks, " week ago", " weeks ago");}private String formatMonths(long months) {return format(months, " month ago", " months ago");}private String formatYears(long years) {return format(years, " year ago", " years ago");}private String format(long hand, String singular, String plural) {if (hand == 1) {return hand + singular;} else {return hand + plural;}}}

  

PS:

Date之常用:

 private static Date date(String string) {try {return new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.UK).parse(string);} catch (ParseException e) {throw new IllegalArgumentException(e);}}private static Date dateIso(String string){try {SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.getDefault());simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));return simpleDateFormat.parse(string);} catch (ParseException e) {throw new IllegalArgumentException(e);}}

  

 

dateIso("2014-02-14T18:40:50Z")TimeStampFormatter t = new TimeStampFormatter();//new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.UK).parse(string)try {System.out.println(t.format(new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA).parse("2016-02-14 09:00")));} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();}

  

PS:Date实现:

 

import java.util.Date;
import java.util.concurrent.TimeUnit;class TimeStampFormatter {/*** For use with java.util.Date*/public String format(Date timestamp) {long millisFromNow = getMillisFromNow(timestamp);long minutesFromNow = TimeUnit.MILLISECONDS.toMinutes(millisFromNow);if (minutesFromNow < 1) {return "just now";}long hoursFromNow = TimeUnit.MILLISECONDS.toHours(millisFromNow);if (hoursFromNow < 1) {return formatMinutes(minutesFromNow);}long daysFromNow = TimeUnit.MILLISECONDS.toDays(millisFromNow);if (daysFromNow < 1) {return formatHours(hoursFromNow);}long weeksFromNow = TimeUnit.MILLISECONDS.toDays(millisFromNow) / 7;if (weeksFromNow < 1) {return formatDays(daysFromNow);}long monthsFromNow = TimeUnit.MILLISECONDS.toDays(millisFromNow) / 30;if (monthsFromNow < 1) {return formatWeeks(weeksFromNow);}long yearsFromNow = TimeUnit.MILLISECONDS.toDays(millisFromNow) / 365;if (yearsFromNow < 1) {return formatMonths(monthsFromNow);}return formatYears(yearsFromNow);}private long getMillisFromNow(Date commentedAt) {long commentedAtMillis = commentedAt.getTime();long nowMillis = System.currentTimeMillis();return nowMillis - commentedAtMillis;}private String formatMinutes(long minutes) {return format(minutes, " minute ago", " minutes ago");}private String formatHours(long hours) {return format(hours, " hour ago", " hours ago");}private String formatDays(long days) {return format(days, " day ago", " days ago");}private String formatWeeks(long weeks) {return format(weeks, " week ago", " weeks ago");}private String formatMonths(long months) {return format(months, " month ago", " months ago");}private String formatYears(long years) {return format(years, " year ago", " years ago");}private String format(long hand, String singular, String plural) {if (hand == 1) {return hand + singular;} else {return hand + plural;}}
}

  

from:http://blog.blundellapps.co.uk/creating-comments-with-timestamps-like-youtube/

 

import java.util.Date;
import java.util.concurrent.TimeUnit;import org.junit.Test;import static org.junit.Assert.assertEquals;public class JavaUtilDate_TimeStampFormatterTest {private static final int DAYS_IN_A_WEEK = 7;private static final int AVERAGE_DAYS_IN_A_MONTH = 30;private static final int DAYS_IN_YEAR = 365; // We don't need the level of accuracy of leap years@Testpublic void givenCommentedUnder60SecondsAgo_thenFormatSaysJustNow() throws Exception {TimeStampFormatter formatter = new TimeStampFormatter();Date commentedAt = minusSeconds(59, now());String commentedAtFormatted = formatter.format(commentedAt);assertEquals("just now", commentedAtFormatted);}@Testpublic void givenCommented1MinuteAgo_thenFormatSays1MinuteAgo() throws Exception {TimeStampFormatter formatter = new TimeStampFormatter();Date commentedAt = minusMinutes(1, now());String commentedAtFormatted = formatter.format(commentedAt);assertEquals("1 minute ago", commentedAtFormatted);}@Testpublic void givenCommentedUnder60MinuteAgo_thenFormatSaysXMinutesAgo() throws Exception {TimeStampFormatter formatter = new TimeStampFormatter();Date commentedAt = minusMinutes(59, minusSeconds(59, now()));String commentedAtFormatted = formatter.format(commentedAt);assertEquals("59 minutes ago", commentedAtFormatted);}@Testpublic void givenCommented1HourAgo_thenFormatSays1HourAgo() throws Exception {TimeStampFormatter formatter = new TimeStampFormatter();Date commentedAt = minusHours(1, now());String commentedAtFormatted = formatter.format(commentedAt);assertEquals("1 hour ago", commentedAtFormatted);}@Testpublic void givenCommentedUnder24HoursAgo_thenFormatSaysXHoursAgo() throws Exception {TimeStampFormatter formatter = new TimeStampFormatter();Date commentedAt = minusHours(23, minusMinutes(59, now()));String commentedAtFormatted = formatter.format(commentedAt);assertEquals("23 hours ago", commentedAtFormatted);}@Testpublic void givenCommented1DayAgo_thenFormatSays1DayAgo() throws Exception {TimeStampFormatter formatter = new TimeStampFormatter();Date commentedAt = minusDays(1, now());String commentedAtFormatted = formatter.format(commentedAt);assertEquals("1 day ago", commentedAtFormatted);}@Testpublic void givenCommentedLessThan7DayAgo_thenFormatSaysXDaysAgo() throws Exception {TimeStampFormatter formatter = new TimeStampFormatter();Date commentedAt = minusDays(6, minusHours(23, minusMinutes(59, now())));String commentedAtFormatted = formatter.format(commentedAt);assertEquals("6 days ago", commentedAtFormatted);}@Testpublic void givenCommented1WeekAgo_thenFormatSays1WeekAgo() throws Exception {TimeStampFormatter formatter = new TimeStampFormatter();Date commentedAt = minusWeeks(1, now());String commentedAtFormatted = formatter.format(commentedAt);assertEquals("1 week ago", commentedAtFormatted);}@Testpublic void givenCommentedLessThan4WeeksAgo_thenFormatSaysXWeeksAgo() throws Exception {TimeStampFormatter formatter = new TimeStampFormatter();Date commentedAt = minusWeeks(3, minusDays(6, minusHours(23, minusMinutes(59, now()))));String commentedAtFormatted = formatter.format(commentedAt);assertEquals("3 weeks ago", commentedAtFormatted);}@Testpublic void givenCommented1MonthAgo_thenFormatSays1MonthAgo() throws Exception {TimeStampFormatter formatter = new TimeStampFormatter();Date commentedAt = minusMonths(1, now());String commentedAtFormatted = formatter.format(commentedAt);assertEquals("1 month ago", commentedAtFormatted);}@Testpublic void givenCommentedLessThan1YearAgo_thenFormatSaysXMonthsAgo() throws Exception {TimeStampFormatter formatter = new TimeStampFormatter();Date commentedAt = minusMonths(11, minusWeeks(3, minusDays(6, minusHours(23, minusMinutes(59, now())))));String commentedAtFormatted = formatter.format(commentedAt);assertEquals("11 months ago", commentedAtFormatted);}@Testpublic void givenCommented1YearAgo_thenFormatSays1YearAgo() throws Exception {TimeStampFormatter formatter = new TimeStampFormatter();Date commentedAt = minusYears(1, now());String commentedAtFormatted = formatter.format(commentedAt);assertEquals("1 year ago", commentedAtFormatted);}@Testpublic void givenCommentedOver1YearAgo_thenFormatSaysXYearsAgo() throws Exception {TimeStampFormatter formatter = new TimeStampFormatter();Date commentedAt = minusYears(2, minusMonths(11, minusWeeks(3, minusDays(6, minusHours(23, minusMinutes(59, now()))))));String commentedAtFormatted = formatter.format(commentedAt);assertEquals("2 years ago", commentedAtFormatted);}private Date minusSeconds(int seconds, Date date) {return minus(date, TimeUnit.SECONDS.toMillis(seconds));}private Date minusMinutes(int minutes, Date date) {return minus(date, TimeUnit.MINUTES.toMillis(minutes));}private Date minusHours(int hours, Date date) {return minus(date, TimeUnit.HOURS.toMillis(hours));}private Date minusDays(int days, Date date) {return minus(date, TimeUnit.DAYS.toMillis(days));}private Date minusWeeks(int weeks, Date date) {return minus(date, TimeUnit.DAYS.toMillis(weeks * DAYS_IN_A_WEEK));}private Date minusMonths(int months, Date date) {return minus(date, TimeUnit.DAYS.toMillis(months * AVERAGE_DAYS_IN_A_MONTH));}private Date minusYears(int years, Date date) {return minus(date, TimeUnit.DAYS.toMillis(years * DAYS_IN_YEAR));}private Date minus(Date date, long minutesInMillis) {date.setTime(date.getTime() - minutesInMillis);return date;}private Date now() {return new Date();}
}

  

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/261918.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

android lint工作机制,Android架构

MVCmvc model view controller 模式视图控制器M: 业务逻辑处理V&#xff1a;处理数据显示的部分C&#xff1a;Activity处理用户交互的问题&#xff0c;中间桥梁的作用&#xff0c;解耦的作用。特点&#xff1a;耦合性低扩展性好&#xff0c;利于维护模块职责划分明确Model层&am…

opendds开发指南中文版_最强的开发者技术路线图已经更新到 2020 GitHub 超 118k还有中文...

想必大家都知道&#xff0c;学习路线图是学习一门新技术的入门指南&#xff0c;让我们对技术有一个大概的了解&#xff0c;并且在学习感到困惑时被指导。所谓不求最好&#xff0c;但求最全。今天在在就给大家带来了一个国外大牛开源的项目 — 「developer-roadmap」&#xff0c…

iOS APP网络分析之rvictl(可以捕捉除了Wifi以外的网络类型)

iOS应用&#xff08;包括移动应用&#xff09;的网络分析&#xff0c;一般采用将移动设备上的流量导入到PC机上&#xff0c;利用PC上成熟的数据包分析工具例如wireshark等来进行分析的方法。 总的来说&#xff0c;有以下三种方法&#xff1a;一、在PC上设置网络共享&#xff0c…

oracle批量update数据_东方国信大数据面试真题

东方国信学长1Hadoop工程师笔试题&#xff08;金融事业部&#xff09;1&#xff09;技术基础题&#xff08;共十题&#xff0c;每题5分&#xff09;&#xff08;1&#xff09;列举在Linux系统下可以在看系统各项性能的工具&#xff08;区分CPU、内存、硬盘、网络等&#xff09;…

eclipse定制化配置调优、初始化配置指南、可以解决启动慢等问题

配置eclipse的jvm参数 打开eclipse根目录下的eclipse.ini在最后面加上如下的jvm参数 -Xms400m -Xmx1400m -XX:NewSize128m -XX:MaxNewSize512m -XX:PermSize96m -XX:MaxPermSize128m -server -XX:CompileThreshold100 -XX:UseParNewGC -XX:UseConcMarkSweepGC -XX:CMSInitiatin…

SEC SOC Test Board 在WIN 7下的安装

首先找到“设备和打印机”点击打开 如果你插上了USB线&#xff0c;会看到&#xff0c;安装不成功时会有个“&#xff01;” 双击它&#xff0c;出现 点击“属性”&#xff0c;出现 点击“改变设置”&#xff0c;出现 点击“更新驱动程序”&#xff0c;出现 点击进去&#xff0c…

吴枫 python小课怎么样_编程中,有哪些好的习惯从一开始就值得坚持?

电影《喜剧之王》里&#xff0c;周星驰饰演的尹天仇&#xff0c;是一个渴望成为真正的演员&#xff0c;却不断沦为落魄跑龙套的小人物。即便如此&#xff0c;他对演戏的态度始终认真而可敬。他每天不但锲而不舍寻找演戏机会&#xff0c;还在街坊福利社开了个戏剧训练班&#xf…

设置width不生效_关于padding被计算在width中问题——box-sizing相关

前一阵子遇到一个小问题&#xff0c;在同样的样式&#xff08;主要是宽高边距之类的&#xff09;条件下&#xff0c;DIV在移动端和PC端的宽度不一样&#xff0c;排除了绝大多数样式的问题&#xff0c;但是有个比较陌生&#xff0c;就是box-sizing&#xff0c;其实经常看到&…

我的Python成长之路---第六天---Python基础(19)---2016年2月20日(晴)

shelve模块shelve模块是pickle模块的扩展&#xff0c;可以通过key&#xff0c;value的方式访问pickle持久化保存的数据持久化保存&#xff1a;12345678910111213import shelvesw shelve.open(shelve_test.pkl) # 创建shelve对象name [13, 14, 145, 6] # 创建一个列表dist_tes…

apache 设置404 页面_SpringBoot自定义错误页面

SpringBoot请求错误如404可能看到如下页面&#xff1a;有时可能需要自定义错误页面针对不同的http.status,如404/400。【1】解决方法① 注册错误页面如下所示&#xff1a;Componentpublic class ErrorPageConfig implements ErrorPageRegistrar { Override public void r…

Java 编程:如何提高性能?(简单总结篇)

2019独角兽企业重金招聘Python工程师标准>>> 开发者在编程中除了要有编程规范&#xff0c;还要注意性能&#xff0c;在 Java 编程中有什么提高性能的好办法呢&#xff1f; 本文转自国内 ITOM 行业领军企业 OneAPM Cloud Insight&#xff08;一款能够优雅监控多种操作…

mysql没有开启binlog能恢复数据吗_神了!一个妹子 rm -rf 把公司整个数据库删没了......

经历了两天不懈努力&#xff0c;终于恢复了一次误操作删除的生产服务器数据。对本次事故过程和解决办法记录在此&#xff0c;警醒自己&#xff0c;也提示别人莫犯此错。也希望遇到问题的朋友能找到一丝灵感解决问题。01事故背景安排一个妹子在一台生产服务器上安装 Oracle&…

android手机活跃度,微信Android机型活跃度曝光,这个结果你满意吗?

原标题&#xff1a;微信Android机型活跃度曝光&#xff0c;这个结果你满意吗&#xff1f;在本周的第二届前端开发者大会上&#xff0c;由腾讯微信工程师公布了微信Android客户端机型前十的发布图&#xff0c;说的也是某款手机的存量跟用户活跃度的统计&#xff0c;在这张微信分…

postgresql9.4.4中文手册笔记-9.10 支持枚举函数

2019独角兽企业重金招聘Python工程师标准>>> 创建枚举类型 create type name as ENUM(zhao,qian,sun,li,zhou,wu, zheng,wang,cheng); 支持枚举函数 select enum_first(null::testenum); --查询枚举类型第一个元素 enum_first ------------zhao (1 row) select e…

.NET Framework源码研究系列之---Delegate

前言 曾几何时能看到微软产品的源码简直是天方夜谭,不过现在这却成了现实,微软终于对外开放了它的产品的源代码.抛去开源运动与微软之间的世代情仇,抛去微软这一做法的初衷,这总归是件好事,能够让我们拨开云雾,一窥优秀产品的秘密. 前两天看到有位仁兄在随笔中的留言,说他以为&…

如何设置多个图层层叠关系_如何玩转 XMind 中的多种思维结构?

熟悉 XMind 的用户都知道&#xff0c;XMind 支持多种思维结构&#xff0c;并且不同思维结构可以混用。每一个分支都可以是一个不同的结构&#xff0c;让你不受限制、自由地进行思维的发散和整理。这个是目前其他思维导图工具少有的。在 XMind 中&#xff0c;你可以用思维导图、…

python修改html表格,使用styles和css更改pandas dataframe html表python中...

这需要几个步骤&#xff1a;首先导入HTML并重新输入from IPython.display import HTMLimport re你可以通过to_html方法得到html pandas.df_html df.to_html()接下来,我们将为html表和我们要创建的样式生成随机标识符.random_id id%d % np.random.choice(np.arange(1000000))因…

PHP关于VC11,VC9,VC6以及Thread Safe和Non Thread Safe版本选择

2019独角兽企业重金招聘Python工程师标准>>> 这里是我在搭建php环境时收集的资料供大家参考&#xff1a; 现在PHP官网上下载PHP安装包都有VC11或VC9的字样&#xff0c;这是什么含义&#xff0c;我们应该下载哪种安装包更好呢&#xff1f;其实PHP官网给出了答案&…

Silverlight与WCF之间的通信(5)silverlight应用和wcf服务的发布方法

上一篇博文中有朋友问到关于silverlight程序发布的问题&#xff0c;上一篇写的是silverlight访问host在console上的wcf&#xff0c;其实关于wcf和silverlihgt通信的问题有好几种方式&#xff0c;这里列举了一下 客户端和服务端采用http协议通信&#xff08;分两种&#xff0c;同…

小程序引用其他页面js_来聊聊小程序页面之间如何通信

小程序页面之间如何通信?首先将通信的模型列举出来, 分为以下几种兄弟页面间通信父路径页面向子路径页面通信子路径页面向父路径页面通信通信的方式localStorage 本地存储globalData 全局对象eventBus 发布订阅PageModel 缓存整个pageModel至globalDataLocalStorage利用onShow…