org.joda.time.Hours Java Examples
The following examples show how to use
org.joda.time.Hours.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BaseSingleFieldPeriodRelay.java From jfixture with MIT License | 6 votes |
@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(); }
Example #2
Source File: CalculateDateTimeDifference.java From levelup-java-examples with Apache License 2.0 | 6 votes |
@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); }
Example #3
Source File: Interval.java From program-ab with GNU Lesser General Public License v3.0 | 6 votes |
public static int getHoursBetween(final String date1, final String date2, String format){ try { final DateTimeFormatter fmt = DateTimeFormat .forPattern(format) .withChronology( LenientChronology.getInstance( GregorianChronology.getInstance())); return Hours.hoursBetween( fmt.parseDateTime(date1), fmt.parseDateTime(date2) ).getHours(); } catch (Exception ex) { ex.printStackTrace(); return 0; } }
Example #4
Source File: TestCondensedAnomalyTimelinesView.java From incubator-pinot with Apache License 2.0 | 6 votes |
@Test public void testFromAnomalyTimelinesView() { int testNum = 100; long minBucketMillis = CondensedAnomalyTimelinesView.DEFAULT_MIN_BUCKET_UNIT; CondensedAnomalyTimelinesView condensedView = CondensedAnomalyTimelinesView.fromAnomalyTimelinesView(getTestData(testNum)); Assert.assertEquals(condensedView.bucketMillis.longValue(), Hours.ONE.toStandardDuration().getMillis() / minBucketMillis); Assert.assertEquals(condensedView.getTimeStamps().size(), testNum); DateTime date = new DateTime(2018, 1, 1, 0, 0, 0); for (int i = 0; i < testNum; i++) { Assert.assertEquals(condensedView.getTimeStamps().get(i).longValue(), (date.getMillis() - condensedView.timestampOffset)/minBucketMillis); Assert.assertEquals(condensedView.getCurrentValues().get(i), i + 0d); Assert.assertEquals(condensedView.getBaselineValues().get(i), i + 0.1); date = date.plusHours(1); } }
Example #5
Source File: BusInfoWindowAdapter.java From android-app with GNU General Public License v2.0 | 6 votes |
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)); }
Example #6
Source File: CronExpressionTest.java From actframework with Apache License 2.0 | 6 votes |
@Test public void check_hour_shall_run_23_times_in_DST_change_to_summertime() throws Exception { CronExpression cron = new CronExpression("0 0 * * * *"); DateTime start = new DateTime(2011, 03, 27, 0, 0, 0, 0); DateTime slutt = start.toLocalDate().plusDays(1).toDateTimeAtStartOfDay(); DateTime tid = start; assertThat(Hours.hoursBetween(start, slutt).getHours()).isEqualTo(23); int count=0; DateTime lastTime = tid; while(tid.isBefore(slutt)){ DateTime nextTime = cron.nextTimeAfter(tid); assertThat(nextTime.isAfter(lastTime)).isTrue(); lastTime = nextTime; tid = tid.plusHours(1); count++; } assertThat(count).isEqualTo(23); }
Example #7
Source File: CronExpressionTest.java From actframework with Apache License 2.0 | 6 votes |
@Test public void check_hour_shall_run_25_times_in_DST_change_to_wintertime() throws Exception { CronExpression cron = new CronExpression("0 1 * * * *"); DateTime start = new DateTime(2011, 10, 30, 0, 0, 0, 0); DateTime slutt = start.toLocalDate().plusDays(1).toDateTimeAtStartOfDay(); DateTime tid = start; assertThat(Hours.hoursBetween(start, slutt).getHours()).isEqualTo(25); int count=0; DateTime lastTime = tid; while(tid.isBefore(slutt)){ DateTime nextTime = cron.nextTimeAfter(tid); assertThat(nextTime.isAfter(lastTime)).isTrue(); lastTime = nextTime; tid = tid.plusHours(1); count++; } assertThat(count).isEqualTo(25); }
Example #8
Source File: CronExpressionTest.java From cron with Apache License 2.0 | 6 votes |
@Test public void check_hour_shall_run_23_times_in_DST_change_to_summertime() throws Exception { CronExpression cron = new CronExpression("0 0 * * * *"); DateTime start = new DateTime(2011, 03, 27, 0, 0, 0, 0); DateTime slutt = start.toLocalDate().plusDays(1).toDateTimeAtStartOfDay(); DateTime tid = start; assertThat(Hours.hoursBetween(start, slutt).getHours()).isEqualTo(23); int count=0; DateTime lastTime = tid; while(tid.isBefore(slutt)){ DateTime nextTime = cron.nextTimeAfter(tid); assertThat(nextTime.isAfter(lastTime)).isTrue(); lastTime = nextTime; tid = tid.plusHours(1); count++; } assertThat(count).isEqualTo(23); }
Example #9
Source File: CronExpressionTest.java From cron with Apache License 2.0 | 6 votes |
@Test public void check_hour_shall_run_25_times_in_DST_change_to_wintertime() throws Exception { CronExpression cron = new CronExpression("0 1 * * * *"); DateTime start = new DateTime(2011, 10, 30, 0, 0, 0, 0); DateTime slutt = start.toLocalDate().plusDays(1).toDateTimeAtStartOfDay(); DateTime tid = start; assertThat(Hours.hoursBetween(start, slutt).getHours()).isEqualTo(25); int count=0; DateTime lastTime = tid; while(tid.isBefore(slutt)){ DateTime nextTime = cron.nextTimeAfter(tid); assertThat(nextTime.isAfter(lastTime)).isTrue(); lastTime = nextTime; tid = tid.plusHours(1); count++; } assertThat(count).isEqualTo(25); }
Example #10
Source File: UserService.java From JDeSurvey with GNU Affero General Public License v3.0 | 6 votes |
public boolean user_validateForgotPasswordKey(String hash) { try { PasswordResetRequest passwordResetRequest = passwordResetRequestDAO.findByHash(hash); if (passwordResetRequest == null) {log.info("empty return" + hash);} if (passwordResetRequest != null && passwordResetRequest.getResetDate() == null) { int hours = Hours.hoursBetween(new DateTime(passwordResetRequest.getRequestDate()), new DateTime(new Date())).getHours(); if (hours <= TIME_INTERVAL_TO_CHANGE_PASSWORD_IN_HOURS ) { return true; } } return false; } catch (Exception e) { log.error(e.getMessage(),e); throw (new RuntimeException(e)); } }
Example #11
Source File: TimelineConverter.java From twittererer with Apache License 2.0 | 6 votes |
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 ""; } }
Example #12
Source File: DatetimeUtil.java From stategen with GNU Affero General Public License v3.0 | 6 votes |
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; } }
Example #13
Source File: DateLib.java From CloverETL-Engine with GNU Lesser General Public License v2.1 | 5 votes |
@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; }
Example #14
Source File: FrameworkUtils.java From data-polygamy with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static int getDeltaSinceEpoch(int time, int tempRes) { int delta = 0; // Epoch MutableDateTime epoch = new MutableDateTime(); epoch.setDate(0); DateTime dt = new DateTime(time*1000, DateTimeZone.UTC); switch(tempRes) { case FrameworkUtils.HOUR: Hours hours = Hours.hoursBetween(epoch, dt); delta = hours.getHours(); break; case FrameworkUtils.DAY: Days days = Days.daysBetween(epoch, dt); delta = days.getDays(); break; case FrameworkUtils.WEEK: Weeks weeks = Weeks.weeksBetween(epoch, dt); delta = weeks.getWeeks(); break; case FrameworkUtils.MONTH: Months months = Months.monthsBetween(epoch, dt); delta = months.getMonths(); break; case FrameworkUtils.YEAR: Years years = Years.yearsBetween(epoch, dt); delta = years.getYears(); break; default: hours = Hours.hoursBetween(epoch, dt); delta = hours.getHours(); break; } return delta; }
Example #15
Source File: Functions.java From sana.mobile with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * 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); }
Example #16
Source File: FrameworkUtils.java From data-polygamy with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static int getTimeSteps(int tempRes, int startTime, int endTime) { if (startTime > endTime) { return 0; } int timeSteps = 0; DateTime start = new DateTime(((long)startTime)*1000, DateTimeZone.UTC); DateTime end = new DateTime(((long)endTime)*1000, DateTimeZone.UTC); switch(tempRes) { case FrameworkUtils.HOUR: timeSteps = Hours.hoursBetween(start, end).getHours(); break; case FrameworkUtils.DAY: timeSteps = Days.daysBetween(start, end).getDays(); break; case FrameworkUtils.WEEK: timeSteps = Weeks.weeksBetween(start, end).getWeeks(); break; case FrameworkUtils.MONTH: timeSteps = Months.monthsBetween(start, end).getMonths(); break; case FrameworkUtils.YEAR: timeSteps = Years.yearsBetween(start, end).getYears(); break; default: timeSteps = Hours.hoursBetween(start, end).getHours(); break; } timeSteps++; return timeSteps; }
Example #17
Source File: RelativeDateFormat.java From NaturalDateFormat with Apache License 2.0 | 5 votes |
private void formatHours(DateTime now, DateTime then, StringBuilder text) { int hoursBetween = Hours.hoursBetween(now.toLocalTime(), then.toLocalTime()).getHours(); if (hoursBetween == 0) { if (hasFormat(MINUTES)) { formatMinutes(now, then, text); } else { text.append(context.getString(R.string.now)); } } else if (hoursBetween > 0) { // in N hours text.append(context.getResources().getQuantityString(R.plurals.carbon_inHours, hoursBetween, hoursBetween)); } else { // N hours ago text.append(context.getResources().getQuantityString(R.plurals.carbon_hoursAgo, -hoursBetween, -hoursBetween)); } }
Example #18
Source File: HoursBetweenDates.java From levelup-java-examples with Apache License 2.0 | 5 votes |
@Test public void hours_between_two_dates_in_java_with_joda () { // start day is 1 day in the past DateTime startDate = new DateTime().minusDays(1); DateTime endDate = new DateTime(); Hours hours = Hours.hoursBetween(startDate, endDate); int numberOfHours = hours.getHours(); assertEquals(24, numberOfHours); }
Example #19
Source File: TestDateTimeFunctionsBase.java From presto with Apache License 2.0 | 4 votes |
private static Hours hoursBetween(ReadableInstant start, ReadableInstant end) { return Hours.hoursBetween(start, end); }
Example #20
Source File: TestAllClassDataTypesAreSupported.java From jfixture with MIT License | 4 votes |
@Test public void creates_instance_of_Hours() { Hours hours = fixture.create(Hours.class); assertThat(hours, notNullValue()); assertThat(hours, is(Hours.hours(8760))); }
Example #21
Source File: ShardingStrategyHourly.java From Rhombus with MIT License | 4 votes |
public long getShardKey(long timestamp){ DateTime d = new DateTime(timestamp, DateTimeZone.UTC); DateTime start = new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC); int daysSinceEpoch = Hours.hoursBetween(start, d).getHours(); return this.offset + daysSinceEpoch; }
Example #22
Source File: DateUtilTest.java From commcare-android with Apache License 2.0 | 3 votes |
@Test public void testDateCalculations() { //Test Identity Calculations Date now = new Date(); LocalDateTime ldnow = new LocalDateTime(now); DateTime dtnow = new DateTime(now); Assert.assertEquals("Dates are incompatible (Date -> LocalDate)", now.getTime(), ldnow.toDate().getTime()); Assert.assertEquals("Dates are incompatible (Date -> DateTime)", now.getTime(), dtnow.toLocalDateTime().toDate().getTime()); DateTime elevenPm = new DateTime(2020, 10, 10, 23, 00, 00); DateTime twoAmNd = elevenPm.plus(Hours.hours(4)); DateTime elevenThirtyPmNd = new DateTime(2020, 10, 11, 23, 30, 00); DateTime elevenPmPlusThree = elevenPm.plus(Hours.hours(72)); DateTime elevenPmPlusThreeDaysThirtyMinutes = elevenPm.plus(Hours.hours(72).plus(Minutes.minutes(30).toStandardHours())); DateTime elevenPmPlusThreeDaysOneHour = elevenPm.plus(Hours.hours(73)); Assert.assertEquals(1, SyncDetailCalculations.getDaysBetweenJavaDatetimes(elevenPm.toDate(), twoAmNd.toDate())); Assert.assertEquals(0, SyncDetailCalculations.getDaysBetweenJavaDatetimes(twoAmNd.toDate(), elevenThirtyPmNd.toDate())); Assert.assertEquals(3, SyncDetailCalculations.getDaysBetweenJavaDatetimes(elevenPm.toDate(), elevenPmPlusThree.toDate())); Assert.assertEquals(3, SyncDetailCalculations.getDaysBetweenJavaDatetimes(elevenPm.toDate(), elevenPmPlusThreeDaysThirtyMinutes.toDate())); Assert.assertEquals(4, SyncDetailCalculations.getDaysBetweenJavaDatetimes(elevenPm.toDate(), elevenPmPlusThreeDaysOneHour.toDate())); }
Example #23
Source File: DateTimeService.java From hawkular-metrics with Apache License 2.0 | 2 votes |
/** * @return A DateTime object rounded down to the start of the current hour. For example, if the current time is * 17:21:09, then 17:00:00 is returned. */ public static DateTime currentHour() { return getTimeSlice(now.get(), Hours.ONE.toStandardDuration()); }