List of usage examples for java.time LocalDateTime minusMonths
public LocalDateTime minusMonths(long months)
From source file:Main.java
public static void main(String[] args) { LocalDateTime a = LocalDateTime.of(2014, 6, 30, 12, 00); LocalDateTime t = a.minusMonths(10); System.out.println(t);// www. j a v a 2 s . c o m }
From source file:org.ambraproject.rhino.rest.controller.ArticleCrudController.java
/** * Calculate the date range using the specified rule. For example: * * <ul>//from w w w . j a va 2s. c om * <li>sinceRule=2y - 2 years</li> * <li>sinceRule=5m - 5 months</li> * <li>sinceRule=10d - 10 days</li> * <li>sinceRule=5h - 5 hours</li> * <li>sinceRule=33 - 33 minutes</li> * </ul> * * The method will result in a {@link java.util.Map Map} containing the following keys: * * <ul> * <li><b>fromDate</b> - the starting date * <li><b>toDate</b> - the ending date, which will be the current system date (i.e. now()) * </ul> * * @param sinceRule The rule to calculate the date range * * @return A {@link java.util.Map Map} */ public static final Map<String, LocalDateTime> calculateDateRange(String sinceRule) { if (StringUtils.isBlank(sinceRule)) { return ImmutableMap.of(); } final String timeDesignation = StringUtils.right(sinceRule, 1); long timeDelta = 0; try { // Assume last character is NOT a letter (i.e. all characters are digits). timeDelta = Long.parseLong(sinceRule); } catch (NumberFormatException exception) { // If an exception, then last character MUST have been a letter, // so we now exclude the last character and re-try conversion. try { timeDelta = Long.parseLong(sinceRule.substring(0, sinceRule.length() - 1)); } catch (NumberFormatException error) { log.warn("Failed to convert {} to a timeDelta/timeDesignation!", sinceRule); timeDelta = 0; } } if (timeDelta < 1) { return ImmutableMap.of(); } final LocalDateTime toDate = LocalDateTime.now(); final LocalDateTime fromDate; if (timeDesignation.equalsIgnoreCase("y")) { fromDate = toDate.minusYears(timeDelta); } else if (timeDesignation.equalsIgnoreCase("m")) { fromDate = toDate.minusMonths(timeDelta); } else if (timeDesignation.equalsIgnoreCase("d")) { fromDate = toDate.minusDays(timeDelta); } else if (timeDesignation.equalsIgnoreCase("h")) { fromDate = toDate.minus(timeDelta, ChronoUnit.HOURS); } else { fromDate = toDate.minus(timeDelta, ChronoUnit.MINUTES); } final ImmutableMap<String, LocalDateTime> dateRange = ImmutableMap.of(FROM_DATE, fromDate, TO_DATE, toDate); return dateRange; }