如何在Java中计算“以前”?

在Ruby on Rails中,有一个function可以让你取得任何date,并打印出“很久以前”的样子。

例如:

8 minutes ago 8 hours ago 8 days ago 8 months ago 8 years ago 

在Java中有这样一个简单的方法吗?

看看PrettyTime库。

使用非常简单:

 import org.ocpsoft.prettytime.PrettyTime; PrettyTime p = new PrettyTime(); System.out.println(p.format(new Date())); // prints "moments ago" 

您还可以传入国际化消息的区域设置:

 PrettyTime p = new PrettyTime(new Locale("fr")); System.out.println(p.format(new Date())); // prints "à l'instant" 

正如在评论中指出的,Android有这个function内置到android.text.format.DateUtils类。

您是否考虑过TimeUnit枚举? 这对于这种事情可能非常有用

  try { SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); Date past = format.parse("01/10/2010"); Date now = new Date(); System.out.println(TimeUnit.MILLISECONDS.toMillis(now.getTime() - past.getTime()) + " milliseconds ago"); System.out.println(TimeUnit.MILLISECONDS.toMinutes(now.getTime() - past.getTime()) + " minutes ago"); System.out.println(TimeUnit.MILLISECONDS.toHours(now.getTime() - past.getTime()) + " hours ago"); System.out.println(TimeUnit.MILLISECONDS.toDays(now.getTime() - past.getTime()) + " days ago"); } catch (Exception j){ j.printStackTrace(); } 
  public class TimeUtils { public final static long ONE_SECOND = 1000; public final static long SECONDS = 60; public final static long ONE_MINUTE = ONE_SECOND * 60; public final static long MINUTES = 60; public final static long ONE_HOUR = ONE_MINUTE * 60; public final static long HOURS = 24; public final static long ONE_DAY = ONE_HOUR * 24; private TimeUtils() { } /** * converts time (in milliseconds) to human-readable format * "<w> days, <x> hours, <y> minutes and (z) seconds" */ public static String millisToLongDHMS(long duration) { StringBuffer res = new StringBuffer(); long temp = 0; if (duration >= ONE_SECOND) { temp = duration / ONE_DAY; if (temp > 0) { duration -= temp * ONE_DAY; res.append(temp).append(" day").append(temp > 1 ? "s" : "") .append(duration >= ONE_MINUTE ? ", " : ""); } temp = duration / ONE_HOUR; if (temp > 0) { duration -= temp * ONE_HOUR; res.append(temp).append(" hour").append(temp > 1 ? "s" : "") .append(duration >= ONE_MINUTE ? ", " : ""); } temp = duration / ONE_MINUTE; if (temp > 0) { duration -= temp * ONE_MINUTE; res.append(temp).append(" minute").append(temp > 1 ? "s" : ""); } if (!res.toString().equals("") && duration >= ONE_SECOND) { res.append(" and "); } temp = duration / ONE_SECOND; if (temp > 0) { res.append(temp).append(" second").append(temp > 1 ? "s" : ""); } return res.toString(); } else { return "0 second"; } } public static void main(String args[]) { System.out.println(millisToLongDHMS(123)); System.out.println(millisToLongDHMS((5 * ONE_SECOND) + 123)); System.out.println(millisToLongDHMS(ONE_DAY + ONE_HOUR)); System.out.println(millisToLongDHMS(ONE_DAY + 2 * ONE_SECOND)); System.out.println(millisToLongDHMS(ONE_DAY + ONE_HOUR + (2 * ONE_MINUTE))); System.out.println(millisToLongDHMS((4 * ONE_DAY) + (3 * ONE_HOUR) + (2 * ONE_MINUTE) + ONE_SECOND)); System.out.println(millisToLongDHMS((5 * ONE_DAY) + (4 * ONE_HOUR) + ONE_MINUTE + (23 * ONE_SECOND) + 123)); System.out.println(millisToLongDHMS(42 * ONE_DAY)); /* output : 0 second 5 seconds 1 day, 1 hour 1 day and 2 seconds 1 day, 1 hour, 2 minutes 4 days, 3 hours, 2 minutes and 1 second 5 days, 4 hours, 1 minute and 23 seconds 42 days */ } } 

更多@ 以毫秒为单位将持续时间格式化为可读格式

我拿RealHowTo和Ben J回答并且做我自己的版本:

 public class TimeAgo { public static final List<Long> times = Arrays.asList( TimeUnit.DAYS.toMillis(365), TimeUnit.DAYS.toMillis(30), TimeUnit.DAYS.toMillis(1), TimeUnit.HOURS.toMillis(1), TimeUnit.MINUTES.toMillis(1), TimeUnit.SECONDS.toMillis(1) ); public static final List<String> timesString = Arrays.asList("year","month","day","hour","minute","second"); public static String toDuration(long duration) { StringBuffer res = new StringBuffer(); for(int i=0;i< TimeAgo.times.size(); i++) { Long current = TimeAgo.times.get(i); long temp = duration/current; if(temp>0) { res.append(temp).append(" ").append( TimeAgo.timesString.get(i) ).append(temp != 1 ? "s" : "").append(" ago"); break; } } if("".equals(res.toString())) return "0 seconds ago"; else return res.toString(); } public static void main(String args[]) { System.out.println(toDuration(123)); System.out.println(toDuration(1230)); System.out.println(toDuration(12300)); System.out.println(toDuration(123000)); System.out.println(toDuration(1230000)); System.out.println(toDuration(12300000)); System.out.println(toDuration(123000000)); System.out.println(toDuration(1230000000)); System.out.println(toDuration(12300000000L)); System.out.println(toDuration(123000000000L)); }} 

这将打印以下内容

 0 second ago 1 second ago 12 seconds ago 2 minutes ago 20 minutes ago 3 hours ago 1 day ago 14 days ago 4 months ago 3 years ago 

这是基于RealHowTo的答案,所以如果你喜欢它,也给他/她一些爱。

这个清理版本允许你指定你可能感兴趣的时间范围。

它也处理“和”部分有点不同。 我经常发现,当使用分隔符连接string时,更容易跳过复杂的逻辑,并在完成时删除最后一个分隔符。

 import java.util.concurrent.TimeUnit; import static java.util.concurrent.TimeUnit.MILLISECONDS; public class TimeUtils { /** * Converts time to a human readable format within the specified range * * @param duration the time in milliseconds to be converted * @param max the highest time unit of interest * @param min the lowest time unit of interest */ public static String formatMillis(long duration, TimeUnit max, TimeUnit min) { StringBuilder res = new StringBuilder(); TimeUnit current = max; while (duration > 0) { long temp = current.convert(duration, MILLISECONDS); if (temp > 0) { duration -= current.toMillis(temp); res.append(temp).append(" ").append(current.name().toLowerCase()); if (temp < 2) res.deleteCharAt(res.length() - 1); res.append(", "); } if (current == min) break; current = TimeUnit.values()[current.ordinal() - 1]; } // clean up our formatting.... // we never got a hit, the time is lower than we care about if (res.lastIndexOf(", ") < 0) return "0 " + min.name().toLowerCase(); // yank trailing ", " res.deleteCharAt(res.length() - 2); // convert last ", " to " and" int i = res.lastIndexOf(", "); if (i > 0) { res.deleteCharAt(i); res.insert(i, " and"); } return res.toString(); } } 

小代码给它一个旋风:

 import static java.util.concurrent.TimeUnit.*; public class Main { public static void main(String args[]) { long[] durations = new long[]{ 123, SECONDS.toMillis(5) + 123, DAYS.toMillis(1) + HOURS.toMillis(1), DAYS.toMillis(1) + SECONDS.toMillis(2), DAYS.toMillis(1) + HOURS.toMillis(1) + MINUTES.toMillis(2), DAYS.toMillis(4) + HOURS.toMillis(3) + MINUTES.toMillis(2) + SECONDS.toMillis(1), DAYS.toMillis(5) + HOURS.toMillis(4) + MINUTES.toMillis(1) + SECONDS.toMillis(23) + 123, DAYS.toMillis(42) }; for (long duration : durations) { System.out.println(TimeUtils.formatMillis(duration, DAYS, SECONDS)); } System.out.println("\nAgain in only hours and minutes\n"); for (long duration : durations) { System.out.println(TimeUtils.formatMillis(duration, HOURS, MINUTES)); } } } 

这将输出以下内容:

 0 seconds 5 seconds 1 day and 1 hour 1 day and 2 seconds 1 day, 1 hour and 2 minutes 4 days, 3 hours, 2 minutes and 1 second 5 days, 4 hours, 1 minute and 23 seconds 42 days Again in only hours and minutes 0 minutes 0 minutes 25 hours 24 hours 25 hours and 2 minutes 99 hours and 2 minutes 124 hours and 1 minute 1008 hours 

而且如果有人需要它,这里有一个类将会把上面的string转换成毫秒 。 让人们用可读的文本指定各种事物的超时是非常有用的。

有一个简单的方法来做到这一点:

假设你想要20分钟前的时间:

 Long minutesAgo = new Long(20); Date date = new Date(); Date dateIn_X_MinAgo = new Date (date.getTime() - minutesAgo*60*1000); 

而已..

如果你正在寻找一个简单的“今天”,“昨天”或“x天前”。

 private String getDaysAgo(Date date){ long days = (new Date().getTime() - date.getTime()) / 86400000; if(days == 0) return "Today"; else if(days == 1) return "Yesterday"; else return days + " days ago"; } 

java.time

使用Java 8及更高版本中内置的java.time框架。

 LocalDateTime t1 = LocalDateTime.of(2015, 1, 1, 0, 0, 0); LocalDateTime t2 = LocalDateTime.now(); Period period = Period.between(t1.toLocalDate(), t2.toLocalDate()); Duration duration = Duration.between(t1, t2); System.out.println("First January 2015 is " + period.getYears() + " years ago"); System.out.println("First January 2015 is " + period.getMonths() + " months ago"); System.out.println("First January 2015 is " + period.getDays() + " days ago"); System.out.println("First January 2015 is " + duration.toHours() + " hours ago"); System.out.println("First January 2015 is " + duration.toMinutes() + " minutes ago"); 

关于内置解决scheme:

Java没有任何格式化相对时间的内置支持,也不是Java-8及其新包java.time 。 如果你只需要英文而没有其他的东西,那么只有一个手工的解决scheme可能是可以接受的 – 请参阅@RealHowTo的答案(虽然它有强大的缺点,不考虑瞬间三angular洲到当地时间的翻译时区单位!)。 无论如何,如果你想避免本土复杂的变通办法,尤其是其他地区,那么你需要一个外部库。

在后一种情况下,我build议使用我的库Time4J (或Android上的Time4A)。 它提供了最大的灵活性和最国际化的力量 。 net.time4j.PrettyTime类有七个方法printRelativeTime...(...)用于此目的。 使用testing时钟作为时间源的示例:

 TimeSource<?> clock = () -> PlainTimestamp.of(2015, 8, 1, 10, 24, 5).atUTC(); Moment moment = PlainTimestamp.of(2015, 8, 1, 17, 0).atUTC(); // our input String durationInDays = PrettyTime.of(Locale.GERMAN).withReferenceClock(clock).printRelative( moment, Timezone.of(EUROPE.BERLIN), TimeUnit.DAYS); // controlling the precision System.out.println(durationInDays); // heute (german word for today) 

另一个使用java.time.Instant作为input的例子:

 String relativeTime = PrettyTime.of(Locale.ENGLISH) .printRelativeInStdTimezone(Moment.from(Instant.EPOCH)); System.out.println(relativeTime); // 45 years ago 

该库通过其最新版本(v4.17)支持80种语言以及一些特定国家/地区(特别适用于西class牙语,英语,阿拉伯语,法语)。 国际数据主要基于最新的CLDR版本v29 。 为什么使用这个库的其他重要原因是对多元规则 (在其他语言环境中经常与英语不同), 缩略格式 (例如:“1秒前”)以及考虑时区的expression方式的良好支持。 Time4J甚至在计算相对时间(不是很重要,但形成一个与期望范围相关的信息)的闰秒等异类细节。 与Java-8兼容性存在于易于使用的诸如java.time.Instantjava.time.Periodtypes的转换方法中。

有什么缺点吗? 只有两个。

  • 该库不小(也因为它的大型国际化数据库)。
  • 该API不是很有名,所以社区的知识和支持是不可用的,否则提供的文档是非常详细和全面的。

(紧凑型)备选scheme:

如果您寻找一个更小的解决scheme,并且不需要太多的function,并且愿意容忍与国际化数据相关的可能的质量问题,那么:

  • 我会推荐ocpsoft / PrettyTime (支持实际上32种语言(很快34?)适合于使用java.util.Date – 请参阅@ataylor的答案)。 具有大型社区背景的行业标准CLDR(来自Unicode联盟)不幸地不是国际数据的基础,因此数据的进一步增强或改进可能需要一段时间。

  • 如果你在Android上,那么辅助类android.text.format.DateUtils就是一个小巧的内置select(见这里的其他评论和回答,缺点是它没有几年和几个月的支持,而且我确信只有很less有人喜欢这个辅助类的API风格。

  • 如果你是Joda-Time的粉丝,那么你可以看看它的PeriodFormat类(在版本2.9.4中支持14种语言,另一方面:Joda-Time肯定不是紧凑的,所以我在这里只提到它完整性)。 这个库不是一个真正的答案,因为相对的时间根本不被支持。 至less需要附加文字“ago”(并且手动从生成的列表格式中剥离所有较低的单位 – 很尴尬)。 与Time4J或Android-DateUtils不同的是,它不具有对缩写的自动切换或从相对时间到绝对时间表示的特殊支持。 像PrettyTime一样,它完全依赖于Java社区的私人成员对其国际数据的未经证实的贡献。

我创build了一个jquery-timeago插件的简单Java timeago端口,它可以完成你所要求的function。

 TimeAgo time = new TimeAgo(); String minutes = time.timeAgo(System.currentTimeMillis() - (15*60*1000)); // returns "15 minutes ago" 

乔达时间包,有期间的概念。 你可以用Periods和DateTimes做算术。

从文档 :

 public boolean isRentalOverdue(DateTime datetimeRented) { Period rentalPeriod = new Period().withDays(2).withHours(12); return datetimeRented.plus(rentalPeriod).isBeforeNow(); } 

这不是很漂亮……但我能想到的最接近的就是使用Joda-Time(如本文所述: 如何计算从Joda Time开始的stream逝时间?

如果您正在为Android开发应用程序, 则会为所有此类要求提供实用程序类DateUtils 。 看一下DateUtils#getRelativeTimeSpanString()实用程序的方法。

从文档为

CharSequence getRelativeTimeSpanString(很长一段时间,现在long,long minResolution)

返回描述'time'的string作为相对于'now'的时间。 过去的时间跨度为“42分钟前”。 时间跨度在未来被格式化为“42分钟”。

您将像现在一样将timestampSystem.currentTimeMillis()一起传递。 最小minResolution可让您指定要报告的最小时间范围。

例如,如果将此设置为MINUTE_IN_MILLIS,则过去3秒钟的时间将报告为“0分钟前”。 通过0,MINUTE_IN_MILLIS,HOUR_IN_MILLIS,DAY_IN_MILLIS,WEEK_IN_MILLIS等之一

经过长期的研究,我发现这一点

  public class GetTimeLapse { public static String getlongtoago(long createdAt) { DateFormat userDateFormat = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy"); DateFormat dateFormatNeeded = new SimpleDateFormat("MM/dd/yyyy HH:MM:SS"); Date date = null; date = new Date(createdAt); String crdate1 = dateFormatNeeded.format(date); // Date Calculation DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); crdate1 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(date); // get current date time with Calendar() Calendar cal = Calendar.getInstance(); String currenttime = dateFormat.format(cal.getTime()); Date CreatedAt = null; Date current = null; try { CreatedAt = dateFormat.parse(crdate1); current = dateFormat.parse(currenttime); } catch (java.text.ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Get msec from each, and subtract. long diff = current.getTime() - CreatedAt.getTime(); long diffSeconds = diff / 1000; long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 60 * 1000) % 24; long diffDays = diff / (24 * 60 * 60 * 1000); String time = null; if (diffDays > 0) { if (diffDays == 1) { time = diffDays + "day ago "; } else { time = diffDays + "days ago "; } } else { if (diffHours > 0) { if (diffHours == 1) { time = diffHours + "hr ago"; } else { time = diffHours + "hrs ago"; } } else { if (diffMinutes > 0) { if (diffMinutes == 1) { time = diffMinutes + "min ago"; } else { time = diffMinutes + "mins ago"; } } else { if (diffSeconds > 0) { time = diffSeconds + "secs ago"; } } } } return time; } } 

您可以使用此function计算时间前

  private String timeAgo(long time_ago) { long cur_time = (Calendar.getInstance().getTimeInMillis()) / 1000; long time_elapsed = cur_time - time_ago; long seconds = time_elapsed; int minutes = Math.round(time_elapsed / 60); int hours = Math.round(time_elapsed / 3600); int days = Math.round(time_elapsed / 86400); int weeks = Math.round(time_elapsed / 604800); int months = Math.round(time_elapsed / 2600640); int years = Math.round(time_elapsed / 31207680); // Seconds if (seconds <= 60) { return "just now"; } //Minutes else if (minutes <= 60) { if (minutes == 1) { return "one minute ago"; } else { return minutes + " minutes ago"; } } //Hours else if (hours <= 24) { if (hours == 1) { return "an hour ago"; } else { return hours + " hrs ago"; } } //Days else if (days <= 7) { if (days == 1) { return "yesterday"; } else { return days + " days ago"; } } //Weeks else if (weeks <= 4.3) { if (weeks == 1) { return "a week ago"; } else { return weeks + " weeks ago"; } } //Months else if (months <= 12) { if (months == 1) { return "a month ago"; } else { return months + " months ago"; } } //Years else { if (years == 1) { return "one year ago"; } else { return years + " years ago"; } } } 

1)这里time_ago是微秒

对于Android正如Ravi所说的,但是因为很多人都想在这里复制粘贴这个东西。

  try { SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z"); Date dt = formatter.parse(date_from_server); CharSequence output = DateUtils.getRelativeTimeSpanString (dt.getTime()); your_textview.setText(output.toString()); } catch (Exception ex) { ex.printStackTrace(); your_textview.setText(""); } 

有更多时间的人的解释

  1. 你从某处获得数据。 首先你必须弄清楚它的格式。

防爆。 我从服务器获取数据格式星期三,27一月2016 09:32:35 GMT [这可能不是你的情况]

这是翻译成

SimpleDateFormat formatter = new SimpleDateFormat(“EEE,dd MMM yyyy HH:mm:ss Z”);

我怎么知道的? 阅读这里的文档。

然后,我parsing后,我得到一个date。 那个date我把getRelativeTimeSpanString(没有任何额外的参数是我的罚款,默认为分钟)

如果你没有找出正确的parsingstring就会得到一个exception ,例如: 字符5处的exception。 看看字符5,并更正你的初始分析string。 。 您可能会得到另一个例外,重复此步骤,直到您有正确的公式。

基于这里的一堆答案,我为我的用例创build了以下内容。

用法示例:

 String relativeDate = String.valueOf( TimeUtils.getRelativeTime( 1000L * myTimeInMillis() )); 

 import java.util.Arrays; import java.util.List; import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.SECONDS; /** * Utilities for dealing with dates and times */ public class TimeUtils { public static final List<Long> times = Arrays.asList( DAYS.toMillis(365), DAYS.toMillis(30), DAYS.toMillis(7), DAYS.toMillis(1), HOURS.toMillis(1), MINUTES.toMillis(1), SECONDS.toMillis(1) ); public static final List<String> timesString = Arrays.asList( "yr", "mo", "wk", "day", "hr", "min", "sec" ); /** * Get relative time ago for date * * NOTE: * if (duration > WEEK_IN_MILLIS) getRelativeTimeSpanString prints the date. * * ALT: * return getRelativeTimeSpanString(date, now, SECOND_IN_MILLIS, FORMAT_ABBREV_RELATIVE); * * @param date String.valueOf(TimeUtils.getRelativeTime(1000L * Date/Time in Millis) * @return relative time */ public static CharSequence getRelativeTime(final long date) { return toDuration( Math.abs(System.currentTimeMillis() - date) ); } private static String toDuration(long duration) { StringBuilder sb = new StringBuilder(); for(int i=0;i< times.size(); i++) { Long current = times.get(i); long temp = duration / current; if (temp > 0) { sb.append(temp) .append(" ") .append(timesString.get(i)) .append(temp > 1 ? "s" : "") .append(" ago"); break; } } return sb.toString().isEmpty() ? "now" : sb.toString(); } } 

这是我的这个Java的实现

  public static String relativeDate(Date date){ Date now=new Date(); if(date.before(now)){ int days_passed=(int) TimeUnit.MILLISECONDS.toDays(now.getTime() - date.getTime()); if(days_passed>1)return days_passed+" days ago"; else{ int hours_passed=(int) TimeUnit.MILLISECONDS.toHours(now.getTime() - date.getTime()); if(hours_passed>1)return days_passed+" hours ago"; else{ int minutes_passed=(int) TimeUnit.MILLISECONDS.toMinutes(now.getTime() - date.getTime()); if(minutes_passed>1)return minutes_passed+" minutes ago"; else{ int seconds_passed=(int) TimeUnit.MILLISECONDS.toSeconds(now.getTime() - date.getTime()); return seconds_passed +" seconds ago"; } } } } else { return new SimpleDateFormat("HH:mm:ss MM/dd/yyyy").format(date).toString(); } } 

它适用于我

 public class TimeDifference { int years; int months; int days; int hours; int minutes; int seconds; String differenceString; public TimeDifference(@NonNull Date curdate, @NonNull Date olddate) { float diff = curdate.getTime() - olddate.getTime(); if (diff >= 0) { int yearDiff = Math.round((diff / (AppConstant.aLong * AppConstant.aFloat)) >= 1 ? (diff / (AppConstant.aLong * AppConstant.aFloat)) : 0); if (yearDiff > 0) { years = yearDiff; setDifferenceString(years + (years == 1 ? " year" : " years") + " ago"); } else { int monthDiff = Math.round((diff / AppConstant.aFloat) >= 1 ? (diff / AppConstant.aFloat) : 0); if (monthDiff > 0) { if (monthDiff > AppConstant.ELEVEN) { monthDiff = AppConstant.ELEVEN; } months = monthDiff; setDifferenceString(months + (months == 1 ? " month" : " months") + " ago"); } else { int dayDiff = Math.round((diff / (AppConstant.bFloat)) >= 1 ? (diff / (AppConstant.bFloat)) : 0); if (dayDiff > 0) { days = dayDiff; if (days == AppConstant.THIRTY) { days = AppConstant.TWENTYNINE; } setDifferenceString(days + (days == 1 ? " day" : " days") + " ago"); } else { int hourDiff = Math.round((diff / (AppConstant.cFloat)) >= 1 ? (diff / (AppConstant.cFloat)) : 0); if (hourDiff > 0) { hours = hourDiff; setDifferenceString(hours + (hours == 1 ? " hour" : " hours") + " ago"); } else { int minuteDiff = Math.round((diff / (AppConstant.dFloat)) >= 1 ? (diff / (AppConstant.dFloat)) : 0); if (minuteDiff > 0) { minutes = minuteDiff; setDifferenceString(minutes + (minutes == 1 ? " minute" : " minutes") + " ago"); } else { int secondDiff = Math.round((diff / (AppConstant.eFloat)) >= 1 ? (diff / (AppConstant.eFloat)) : 0); if (secondDiff > 0) { seconds = secondDiff; } else { seconds = 1; } setDifferenceString(seconds + (seconds == 1 ? " second" : " seconds") + " ago"); } } } } } } else { setDifferenceString("Just now"); } } public String getDifferenceString() { return differenceString; } public void setDifferenceString(String differenceString) { this.differenceString = differenceString; } public int getYears() { return years; } public void setYears(int years) { this.years = years; } public int getMonths() { return months; } public void setMonths(int months) { this.months = months; } public int getDays() { return days; } public void setDays(int days) { this.days = days; } public int getHours() { return hours; } public void setHours(int hours) { this.hours = hours; } public int getMinutes() { return minutes; } public void setMinutes(int minutes) { this.minutes = minutes; } public int getSeconds() { return seconds; } public void setSeconds(int seconds) { this.seconds = seconds; } } 

这是非常基本的脚本。 其易于即兴。
结果:( XXX小时前)或(XX天前/昨天/今天)

 <span id='hourpost'></span> ,or <span id='daypost'></span> <script> var postTime = new Date('2017/6/9 00:01'); var now = new Date(); var difference = now.getTime() - postTime.getTime(); var minutes = Math.round(difference/60000); var hours = Math.round(minutes/60); var days = Math.round(hours/24); var result; if (days < 1) { result = "Today"; } else if (days < 2) { result = "Yesterday"; } else { result = days + " Days ago"; } document.getElementById("hourpost").innerHTML = hours + "Hours Ago" ; document.getElementById("daypost").innerHTML = result ; </script>