下面列出了怎么用org.joda.time.Minutes的API类实例代码及写法,或者点击链接到github查看源代码。
protected static int dateDiff(Date beginDate, Date endDate, DateType type) {
//Interval interval = new Interval(beginDate.getTime(), endDate.getTime());
//Period p = interval.toPeriod();
DateTime start =new DateTime(beginDate);
DateTime end =new DateTime(endDate);
if (DateType.YEAR.equals(endDate)) {
return Years.yearsBetween(start, end).getYears();
} else if (DateType.MONTH.equals(type)) {
return Months.monthsBetween(start, end).getMonths();
} else if (DateType.WEEK.equals(type)) {
return Weeks.weeksBetween(start, end).getWeeks();
} else if (DateType.DAY.equals(type)) {
return Days.daysBetween(start, end).getDays();
} else if (DateType.HOUR.equals(type)) {
return Hours.hoursBetween(start, end).getHours();
} else if (DateType.MINUTE.equals(type)) {
return Minutes.minutesBetween(start, end).getMinutes();
} else if (DateType.SECOND.equals(type)) {
return Seconds.secondsBetween(start, end).getSeconds();
} else {
return 0;
}
}
/**
* Gets total size in bytes of all events that remain in Kinesis stream between specified
* instants.
*
* @return total size in bytes of all Kinesis events after specified instant
*/
public long getBacklogBytes(
final String streamName, final Instant countSince, final Instant countTo)
throws TransientKinesisException {
return wrapExceptions(
() -> {
Minutes period = Minutes.minutesBetween(countSince, countTo);
if (period.isLessThan(Minutes.ONE)) {
return 0L;
}
GetMetricStatisticsRequest request =
createMetricStatisticsRequest(streamName, countSince, countTo, period);
long totalSizeInBytes = 0;
GetMetricStatisticsResult result = cloudWatch.getMetricStatistics(request);
for (Datapoint point : result.getDatapoints()) {
totalSizeInBytes += point.getSum().longValue();
}
return totalSizeInBytes;
});
}
@Test
public void shouldCountBytesWhenSingleDataPointReturned() throws Exception {
Instant countSince = new Instant("2017-04-06T10:00:00.000Z");
Instant countTo = new Instant("2017-04-06T11:00:00.000Z");
Minutes periodTime = Minutes.minutesBetween(countSince, countTo);
GetMetricStatisticsRequest metricStatisticsRequest =
underTest.createMetricStatisticsRequest(STREAM, countSince, countTo, periodTime);
GetMetricStatisticsResult result =
new GetMetricStatisticsResult().withDatapoints(new Datapoint().withSum(1.0));
when(cloudWatch.getMetricStatistics(metricStatisticsRequest)).thenReturn(result);
long backlogBytes = underTest.getBacklogBytes(STREAM, countSince, countTo);
assertThat(backlogBytes).isEqualTo(1L);
}
@Test
public void shouldCountBytesWhenMultipleDataPointsReturned() throws Exception {
Instant countSince = new Instant("2017-04-06T10:00:00.000Z");
Instant countTo = new Instant("2017-04-06T11:00:00.000Z");
Minutes periodTime = Minutes.minutesBetween(countSince, countTo);
GetMetricStatisticsRequest metricStatisticsRequest =
underTest.createMetricStatisticsRequest(STREAM, countSince, countTo, periodTime);
GetMetricStatisticsResult result =
new GetMetricStatisticsResult()
.withDatapoints(
new Datapoint().withSum(1.0),
new Datapoint().withSum(3.0),
new Datapoint().withSum(2.0));
when(cloudWatch.getMetricStatistics(metricStatisticsRequest)).thenReturn(result);
long backlogBytes = underTest.getBacklogBytes(STREAM, countSince, countTo);
assertThat(backlogBytes).isEqualTo(6L);
}
private void shouldHandleGetBacklogBytesError(
Exception thrownException, Class<? extends Exception> expectedExceptionClass) {
Instant countSince = new Instant("2017-04-06T10:00:00.000Z");
Instant countTo = new Instant("2017-04-06T11:00:00.000Z");
Minutes periodTime = Minutes.minutesBetween(countSince, countTo);
GetMetricStatisticsRequest metricStatisticsRequest =
underTest.createMetricStatisticsRequest(STREAM, countSince, countTo, periodTime);
when(cloudWatch.getMetricStatistics(metricStatisticsRequest)).thenThrow(thrownException);
try {
underTest.getBacklogBytes(STREAM, countSince, countTo);
failBecauseExceptionWasNotThrown(expectedExceptionClass);
} catch (Exception e) {
assertThat(e).isExactlyInstanceOf(expectedExceptionClass);
} finally {
reset(kinesis);
}
}
private static String dateToAge(String createdAt, DateTime now) {
if (createdAt == null) {
return "";
}
DateTimeFormatter dtf = DateTimeFormat.forPattern(DATE_TIME_FORMAT);
try {
DateTime created = dtf.parseDateTime(createdAt);
if (Seconds.secondsBetween(created, now).getSeconds() < 60) {
return Seconds.secondsBetween(created, now).getSeconds() + "s";
} else if (Minutes.minutesBetween(created, now).getMinutes() < 60) {
return Minutes.minutesBetween(created, now).getMinutes() + "m";
} else if (Hours.hoursBetween(created, now).getHours() < 24) {
return Hours.hoursBetween(created, now).getHours() + "h";
} else {
return Days.daysBetween(created, now).getDays() + "d";
}
} catch (IllegalArgumentException e) {
return "";
}
}
@Override
@SuppressWarnings("EqualsBetweenInconvertibleTypes") // SpecimenType knows how to do equals(Class<?>)
public Object create(Object request, SpecimenContext context) {
if (!(request instanceof SpecimenType)) {
return new NoSpecimen();
}
SpecimenType type = (SpecimenType) request;
if (!BaseSingleFieldPeriod.class.isAssignableFrom(type.getRawType())) {
return new NoSpecimen();
}
Duration duration = (Duration) context.resolve(Duration.class);
if (type.equals(Seconds.class)) return Seconds.seconds(Math.max(1, (int) duration.getStandardSeconds()));
if (type.equals(Minutes.class)) return Minutes.minutes(Math.max(1, (int) duration.getStandardMinutes()));
if (type.equals(Hours.class)) return Hours.hours(Math.max(1, (int) duration.getStandardHours()));
if (type.equals(Days.class)) return Days.days(Math.max(1, (int) duration.getStandardDays()));
if (type.equals(Weeks.class)) return Weeks.weeks(Math.max(1, (int) duration.getStandardDays() / 7));
if (type.equals(Months.class)) return Months.months(Math.max(1, (int) duration.getStandardDays() / 30));
if (type.equals(Years.class)) return Years.years(Math.max(1, (int) duration.getStandardDays() / 365));
return new NoSpecimen();
}
private RepeatingTrigger(Long triggerTime, Long interval, Long delay, Integer repeatCount) {
if (triggerTime != null) {
this.triggerTime = getTimeSlice(triggerTime, standardMinutes(1));
}
else if (interval == null && delay == null) {
this.triggerTime = currentMinute().plusMinutes(1).getMillis();
}
this.interval = interval;
this.delay = delay == null ? Minutes.ONE.toStandardDuration().getMillis() : delay;
this.repeatCount = repeatCount;
this.executionCount = 1;
if (this.triggerTime == null) {
this.triggerTime = getTimeSlice(now.get().getMillis() + this.delay, standardMinutes(1));
}
}
private BitmapDescriptor getIcon(Date data) {
DateTime current = new DateTime(Calendar.getInstance());
DateTime last = new DateTime(data);
int diff = Minutes.minutesBetween(last, current).getMinutes();
BitmapDescriptor bitmap;
if(diff >= 5 && diff < 10 ) {
bitmap = BitmapDescriptorFactory
.fromResource(R.drawable.bus_yellow);
} else if(diff >= 10 ) {
bitmap = BitmapDescriptorFactory
.fromResource(R.drawable.bus_red);
} else {
bitmap = BitmapDescriptorFactory
.fromResource(R.drawable.bus_green);
}
return bitmap;
}
private String prepareDate(Date date){
DateTime busTimestamp = new DateTime(date);
DateTime now = new DateTime(Calendar.getInstance());
int time = Seconds.secondsBetween(busTimestamp, now).getSeconds();
if(time < 60) return context.getString(R.string.marker_seconds, String.valueOf(time));
time = Minutes.minutesBetween(busTimestamp, now).getMinutes();
if(time < 60) return context.getString(R.string.marker_minutes, String.valueOf(time));
time = Hours.hoursBetween(busTimestamp, now).getHours();
if(time < 24) return context.getString(R.string.marker_hours, String.valueOf(time));
time = Days.daysBetween(busTimestamp, now).getDays();
return context.getString(R.string.marker_days, String.valueOf(time));
}
@Test
public void difference_between_two_dates_joda () {
DateTime sinceGraduation = new DateTime(1984, 6, 4, 0, 0, GregorianChronology.getInstance());
DateTime currentDate = new DateTime(); //current date
Days diffInDays = Days.daysBetween(sinceGraduation, currentDate);
Hours diffInHours = Hours.hoursBetween(sinceGraduation, currentDate);
Minutes diffInMinutes = Minutes.minutesBetween(sinceGraduation, currentDate);
Seconds seconds = Seconds.secondsBetween(sinceGraduation, currentDate);
logger.info(diffInDays.getDays());
logger.info(diffInHours.getHours());
logger.info(diffInMinutes.getMinutes());
logger.info(seconds.getSeconds());
assertTrue(diffInDays.getDays() >= 10697);
assertTrue(diffInHours.getHours() >= 256747);
assertTrue(diffInMinutes.getMinutes() >= 15404876);
assertTrue(seconds.getSeconds() >= 924292577);
}
GetMetricStatisticsRequest createMetricStatisticsRequest(
String streamName, Instant countSince, Instant countTo, Minutes period) {
return new GetMetricStatisticsRequest()
.withNamespace(KINESIS_NAMESPACE)
.withMetricName(INCOMING_RECORDS_METRIC)
.withPeriod(period.getMinutes() * PERIOD_GRANULARITY_IN_SECONDS)
.withStartTime(countSince.toDate())
.withEndTime(countTo.toDate())
.withStatistics(Collections.singletonList(SUM_STATISTIC))
.withDimensions(
Collections.singletonList(
new Dimension().withName(STREAM_NAME_DIMENSION).withValue(streamName)));
}
private void formatMinutes(DateTime now, DateTime then, StringBuilder text) {
int minutesBetween = Minutes.minutesBetween(now.toLocalTime(), then.toLocalTime()).getMinutes();
if (minutesBetween == 0) {
if (hasFormat(SECONDS)) {
formatSeconds(now, then, text);
} else {
text.append(context.getString(R.string.now));
}
} else if (minutesBetween > 0) { // in N hours
text.append(context.getResources().getQuantityString(R.plurals.carbon_inMinutes, minutesBetween, minutesBetween));
} else { // N hours ago
text.append(context.getResources().getQuantityString(R.plurals.carbon_minutesAgo, -minutesBetween, -minutesBetween));
}
}
public void moveTo(LocalDateTime current) {
lock.lock();
try {
if (endTime == null) {
init();
} else {
int minutes = Minutes.minutesBetween(endTime, current).getMinutes();
if (minutes <= 0) {
return;
}
if (minutes > values.size()) {
// re-init
init();
} else {
for (int i = 0; i < minutes; i++) {
values.removeFirst();
values.addLast(null);
}
}
}
endTime = current;
} finally {
lock.unlock();
}
if (log.isTraceEnabled()) {
log.trace("Move window {}", transformValues(values));
}
}
public void add(Metrics metrics) {
long bucket = metrics.getTimeBucket();
LocalDateTime timeBucket = TIME_BUCKET_FORMATTER.parseLocalDateTime(bucket + "");
this.lock.lock();
try {
if (this.endTime == null) {
init();
this.endTime = timeBucket;
}
int minutes = Minutes.minutesBetween(timeBucket, this.endTime).getMinutes();
if (minutes < 0) {
this.moveTo(timeBucket);
minutes = 0;
}
if (minutes >= values.size()) {
// too old data
// also should happen, but maybe if agent/probe mechanism time is not right.
if (log.isTraceEnabled()) {
log.trace("Timebucket is {}, endTime is {} and value size is {}", timeBucket, this.endTime, values.size());
}
return;
}
this.values.set(values.size() - minutes - 1, metrics);
} finally {
this.lock.unlock();
}
if (log.isTraceEnabled()) {
log.trace("Add metric {} to window {}", metrics, transformValues(this.values));
}
}
public void start(List<AlarmCallback> allCallbacks) {
LocalDateTime now = LocalDateTime.now();
lastExecuteTime = now;
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
try {
List<AlarmMessage> alarmMessageList = new ArrayList<>(30);
LocalDateTime checkTime = LocalDateTime.now();
int minutes = Minutes.minutesBetween(lastExecuteTime, checkTime).getMinutes();
boolean[] hasExecute = new boolean[] {false};
alarmRulesWatcher.getRunningContext().values().forEach(ruleList -> ruleList.forEach(runningRule -> {
if (minutes > 0) {
runningRule.moveTo(checkTime);
/*
* Don't run in the first quarter per min, avoid to trigger false alarm.
*/
if (checkTime.getSecondOfMinute() > 15) {
hasExecute[0] = true;
alarmMessageList.addAll(runningRule.check());
}
}
}));
// Set the last execute time, and make sure the second is `00`, such as: 18:30:00
if (hasExecute[0]) {
lastExecuteTime = checkTime.minusSeconds(checkTime.getSecondOfMinute());
}
if (alarmMessageList.size() > 0) {
allCallbacks.forEach(callback -> callback.doAlarm(alarmMessageList));
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}, 10, 10, TimeUnit.SECONDS);
}
@TLFunctionAnnotation("Returns the difference between dates")
public static final Long dateDiff(TLFunctionCallContext context, Date lhs, Date rhs, DateFieldEnum unit) {
if (unit == DateFieldEnum.MILLISEC) { // CL-1087
return lhs.getTime() - rhs.getTime();
}
long diff = 0;
switch (unit) {
case SECOND:
// we have the difference in seconds
diff = (long) Seconds.secondsBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getSeconds();
break;
case MINUTE:
// how many minutes'
diff = (long) Minutes.minutesBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getMinutes();
break;
case HOUR:
diff = (long) Hours.hoursBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getHours();
break;
case DAY:
// how many days is the difference
diff = (long) Days.daysBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getDays();
break;
case WEEK:
// how many weeks
diff = (long) Weeks.weeksBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getWeeks();
break;
case MONTH:
diff = (long) Months.monthsBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getMonths();
break;
case YEAR:
diff = (long) Years.yearsBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getYears();
break;
default:
throw new TransformLangExecutorRuntimeException("Unknown time unit " + unit);
}
return diff;
}
public boolean accept(File file) {
boolean result = false;
if (file.getName().matches(getFilenameRegex())) {
LocalDateTime fileLastModifiedDateTime = new LocalDateTime(file.lastModified());
if (Minutes.minutesBetween(fileLastModifiedDateTime, LocalDateTime.now()).getMinutes() > 1) {
result = true;
}
}
return result;
}
/**
* Calculates the difference between two times, given as long values, and
* returns the period between them in the specified <code>units</code>. The
* units value must be one of:
* <pre>
* {@link #MILLISECONDS}
* {@link #SECONDS}
* {@link #MINUTES}
* {@link #HOURS}
* {@link #DAYS}
* {@link #WEEKS}
* {@link #MONTHS}
* {@link #YEARS}
* </pre>
* All values will be returned as the absolute value of the difference.
*
* @param arg1 The value to use as the minuend.
* @param arg2 The value to use as the subtrahend.
* @param units The time units to use for expressing the difference.
* @return The long value of the difference between the arguments in the
* specified units.
*/
public static long period(long arg1, long arg2, int units) {
long delta = arg1 - arg2;
DateTime start = new DateTime(arg1);
DateTime end = new DateTime(arg2);
// Compute delta into appropriate units
switch (units) {
case YEARS:
delta = Years.yearsBetween(start, end).getYears();
break;
case MONTHS:
delta = Months.monthsBetween(start, end).getMonths();
break;
case WEEKS:
delta = Weeks.weeksBetween(start, end).getWeeks();
break;
case DAYS:
delta = Days.daysBetween(start, end).getDays();
break;
case HOURS:
delta = Hours.hoursBetween(start, end).getHours();
break;
case MINUTES:
delta = Minutes.minutesBetween(start, end).getMinutes();
break;
case SECONDS:
delta = Double.valueOf(Math.floor(delta / 1000.0)).longValue();
break;
case MILLISECONDS:
// Here for completeness but already calculated
break;
default:
throw new IllegalArgumentException("Invalid units: "
+ units + " See Functions.difference(Calendar,Calendar)"
+ " for allowed values");
}
return Math.abs(delta);
}
private static Map<String, Double> getPerMinDeltas(final StatTotals totals, final Duration duration) {
final double minutes = (double)duration.getMillis() / (double)Minutes.ONE.toStandardDuration().getMillis();
final Map<String, Double> perMinDeltas = new HashMap<>();
perMinDeltas.put("0-10", totals.getAt10() / Math.min(10.0, Math.max(minutes, 0.0)));
if(minutes > 10.0) {
perMinDeltas.put("10-20", (totals.getAt20() - totals.getAt10()) / Math.min(10.0, minutes - 10.0));
}
if(minutes > 20.0) {
perMinDeltas.put("20-30", (totals.getAt30() - totals.getAt20()) / Math.min(10.0, minutes - 20.0));
}
if(minutes > 30.0) {
perMinDeltas.put("30-end", (totals.getAtGameEnd() - totals.getAt30()) / Math.min(10.0, minutes - 30.0));
}
return perMinDeltas;
}
public double hoursAfter(int hour) {
HourMinuteSecond afterHour = new HourMinuteSecond(hour, 0, 0);
if (!getBeginHourMinuteSecond().isBefore(afterHour)) {
return getUnitHours().doubleValue();
} else if (getEndHourMinuteSecond().isAfter(afterHour)) {
return BigDecimal.valueOf(Minutes.minutesBetween(afterHour, getEndHourMinuteSecond()).getMinutes())
.divide(BigDecimal.valueOf(NUMBER_OF_MINUTES_IN_HOUR), 2, RoundingMode.HALF_UP).doubleValue();
}
return 0.0;
}
private static Minutes minutesBetween(ReadableInstant start, ReadableInstant end)
{
return Minutes.minutesBetween(start, end);
}
private int getOldestDateDifference(List<PumpHistoryEntry> treatments) {
long dt = Long.MAX_VALUE;
PumpHistoryEntry currentTreatment = null;
if (isCollectionEmpty(treatments)) {
return 8; // default return of 6 (5 for diif on history reading + 2 for max allowed difference) minutes
}
for (PumpHistoryEntry treatment : treatments) {
if (treatment.atechDateTime < dt) {
dt = treatment.atechDateTime;
currentTreatment = treatment;
}
}
LocalDateTime oldestEntryTime = null;
try {
oldestEntryTime = DateTimeUtil.toLocalDateTime(dt);
oldestEntryTime = oldestEntryTime.minusMinutes(3);
// if (this.pumpTime.timeDifference < 0) {
// oldestEntryTime = oldestEntryTime.plusSeconds(this.pumpTime.timeDifference);
// }
} catch (Exception ex) {
LOG.error("Problem decoding date from last record: {}" + currentTreatment);
return 8; // default return of 6 minutes
}
LocalDateTime now = new LocalDateTime();
Minutes minutes = Minutes.minutesBetween(oldestEntryTime, now);
// returns oldest time in history, with calculated time difference between pump and phone, minus 5 minutes
if (isLogEnabled())
LOG.debug("Oldest entry: {}, pumpTimeDifference={}, newDt={}, currentTime={}, differenceMin={}", dt,
this.pumpTime.timeDifference, oldestEntryTime, now, minutes.getMinutes());
return minutes.getMinutes();
}
public int getMinutesBeforeEvent() {
return Minutes.minutesBetween(new DateTime(getDate()), new DateTime(dateEvent)).getMinutes();
}
@Provides
@Parameter("delaySeconds")
static int provideDelaySeconds(HttpServletRequest req) {
return extractOptionalIntParameter(req, "delaySeconds")
.orElse(Minutes.ONE.toStandardSeconds().getSeconds());
}
@Provides
@Parameter("runSeconds")
static int provideRunSeconds(HttpServletRequest req) {
return extractOptionalIntParameter(req, "runSeconds")
.orElse(Minutes.ONE.toStandardSeconds().getSeconds());
}
@Test
public void creates_instance_of_Minutes() {
Minutes minutes = fixture.create(Minutes.class);
assertThat(minutes, notNullValue());
assertThat(minutes, is(Minutes.minutes(525600)));
}
private int getUnitMinutes() {
return Minutes.minutesBetween(getBeginHourMinuteSecond(), getEndHourMinuteSecond()).getMinutes();
}
public Duration getTotalDuration() {
return Minutes.minutesBetween(getBeginHourMinuteSecond(), getEndHourMinuteSecond()).toStandardDuration();
}
private int getUnitMinutes() {
return Minutes.minutesBetween(getStartTime(), getEndTime()).getMinutes();
}