public boolean isRentalOverdue(DateTime datetimeRented) {
Period rentalPeriod = new Period().withDays(2).withHours(12);
return datetimeRented.plus(rentalPeriod).isBeforeNow();
}
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
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作为输入的例子:
String relativeTime =
PrettyTime.of(Locale.ENGLISH)
.printRelativeInStdTimezone(Moment.from(Instant.EPOCH));
System.out.println(relativeTime); // 45 years ago
<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>
我正在使用 Instant、 Date 和 DateTimeUtils。
以 String 类型存储在数据库中的数据(日期) ,然后转换为 Instant。
/*
This method is to display ago.
Example: 3 minutes ago.
I already implement the latest which is including the Instant.
Convert from String to Instant and then parse to Date.
*/
public String convertTimeToAgo(String dataDate) {
//Initialize
String conversionTime = null;
String suffix = "Yang Lalu";
Date pastTime;
//Parse from String (which is stored as Instant.now().toString()
//And then convert to become Date
Instant instant = Instant.parse(dataDate);
pastTime = DateTimeUtils.toDate(instant);
//Today date
Date nowTime = new Date();
long dateDiff = nowTime.getTime() - pastTime.getTime();
long second = TimeUnit.MILLISECONDS.toSeconds(dateDiff);
long minute = TimeUnit.MILLISECONDS.toMinutes(dateDiff);
long hour = TimeUnit.MILLISECONDS.toHours(dateDiff);
long day = TimeUnit.MILLISECONDS.toDays(dateDiff);
if (second < 60) {
conversionTime = second + " Saat " + suffix;
} else if (minute < 60) {
conversionTime = minute + " Minit " + suffix;
} else if (hour < 24) {
conversionTime = hour + " Jam " + suffix;
} else if (day >= 7) {
if (day > 30) {
conversionTime = (day / 30) + " Bulan " + suffix;
} else if (day > 360) {
conversionTime = (day / 360) + " Tahun " + suffix;
} else {
conversionTime = (day / 7) + " Minggu " + suffix;
}
} else if (day < 7) {
conversionTime = day + " Hari " + suffix;
}
return conversionTime;
}
Instant now = Instant.now(); // Capture the current moment as seen in UTC.
Instant then = now.minus( 8L , ChronoUnit.HOURS ).minus( 8L , ChronoUnit.MINUTES ).minus( 8L , ChronoUnit.SECONDS );
Duration d = Duration.between( then , now );
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
// Replace ZoneId.systemDefault() with the applicable timezone ID e.g.
// ZoneId.of("Europe/London"). For LocalDate in the JVM's timezone, simply use
// LocalDate.now()
LocalDate endDate = LocalDate.now(ZoneId.systemDefault());
// Let's assume the start date is 1 year, 2 months, and 3 days ago
LocalDate startDate = endDate.minusYears(1).minusMonths(2).minusDays(3);
Period period = Period.between(startDate, endDate);
// Default format
System.out.println(period);
// Custom format
String formattedElapsedPeriod = String.format("%d years, %d months, %d days ago", period.getYears(),
period.getMonths(), period.getDays());
System.out.println(formattedElapsedPeriod);
}
}
产出:
P1Y2M3D
1 years, 2 months, 3 days ago
从 Rel = “ nofollow noReferrer”> Trail: Date Time 了解现代日期时间 API。