我想找出下一个3PM纽约时间和当前时间之间的毫秒差异。即如果现在是纽约时间下午5点。我应该在第二天下午5点到纽约时间下午3点之间得到区别。我怎么能用Java做呢?我很高兴使用JodaTime,请你做一个例子,如何做到这一点。
请帮忙。
答案 0 :(得分:4)
以下是使用最流行的库选择的三种解决方案。它们都遵循相同的模式,只使用给定库的命名法。
DateTime dt = new DateTime(DateTimeZone.forID("US/Eastern"));
DateTime target = dt
.withHourOfDay(15)
.withMinuteOfHour(0)
.withSecondOfMinute(0)
.withMillisOfSecond(0);
if (target.isBefore(dt)) {
target = target.plusDays(1);
}
System.out.println(target.getMillis() - dt.getMillis());
非常喜欢until()
方法:
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("US/Eastern"));
ZonedDateTime target2 = zdt
.withHour(15)
.withMinute(0)
.withSecond(0)
.withNano(0);
if (target2.isBefore(zdt)) {
zdt = zdt.plusDays(1);
}
System.out.println(zdt.until(target2, ChronoUnit.MILLIS));
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("US/Eastern"));
Calendar target3 = Calendar.getInstance(TimeZone.getTimeZone("US/Eastern"));
target3.set(Calendar.HOUR_OF_DAY, 15);
target3.set(Calendar.MINUTE, 0);
target3.set(Calendar.SECOND, 0);
target3.set(Calendar.MILLISECOND, 0);
if (target3.before(c)) {
target3.add(Calendar.DATE, 1);
}
System.out.println(target3.getTimeInMillis() - c.getTimeInMillis());
答案 1 :(得分:1)
这个怎么样?
Date now = new Date();
Calendar ny3pmCalendar = new GregorianCalendar(TimeZone.getTimeZone("America/New_York"));
ny3pmCalendar.setTime(now);
if(ny3pmCalendar.get(Calendar.HOUR_OF_DAY) >= 15) {
// next day
ny3pmCalendar.add(Calendar.DAY_OF_YEAR, 1);
}
ny3pmCalendar.set(Calendar.HOUR, 15);
ny3pmCalendar.set(Calendar.MINUTE, 0);
ny3pmCalendar.set(Calendar.SECOND, 0);
ny3pmCalendar.set(Calendar.MILLISECOND, 0);
long diff = ny3pmCalendar.getTimeInMillis() - now.getTime();
System.out.println(diff);
答案 2 :(得分:0)
尝试joda DateTime和Period
Date oldDate = new Date();
DateTime old = new DateTime(oldDate);
DateTime now = new DateTime();
Period period = new Period(old, now, PeriodType.yearMonthDayTime());
period.getYears();// give the difference in year
period.getMonths();
period.getDays();
period.getMinutes();
period.getSeconds();
Joda Time - 它具有许多日期时间操作功能