Example usage for org.apache.commons.lang3.time DateUtils round

List of usage examples for org.apache.commons.lang3.time DateUtils round

Introduction

In this page you can find the example usage for org.apache.commons.lang3.time DateUtils round.

Prototype

public static Date round(final Object date, final int field) 

Source Link

Document

Rounds a date, leaving the field specified as the most significant field.

For example, if you had the date-time of 28 Mar 2002 13:45:01.231, if this was passed with HOUR, it would return 28 Mar 2002 14:00:00.000.

Usage

From source file:SampleLang.java

public static void checkDate() throws InterruptedException, ParseException {
    //date1 created
    Date date1 = new Date();
    //Print the date and time at this instant
    System.out.println("The time right now is >>" + date1);
    //Thread sleep for 1000 ms
    Thread.currentThread().sleep(DateUtils.MILLIS_PER_MINUTE);
    //date2 created.
    Date date2 = new Date();
    //Check if date1 and date2 have the same day
    System.out.println("Is Same Day >> " + DateUtils.isSameDay(date1, date2));
    //Check if date1 and date2 have the same instance
    System.out.println("Is Same Instant >> " + DateUtils.isSameInstant(date1, date2));
    //Round the hour
    System.out.println("Date after rounding >>" + DateUtils.round(date1, Calendar.HOUR));
    //Truncate the hour
    System.out.println("Date after truncation >>" + DateUtils.truncate(date1, Calendar.HOUR));
    //Three dates in three different formats
    String[] dates = { "2005.03.24 11:03:26", "2005-03-24 11:03", "2005/03/24" };
    //Iterate over dates and parse strings to java.util.Date objects
    for (int i = 0; i < dates.length; i++) {
        Date parsedDate = DateUtils.parseDate(dates[i],
                new String[] { "yyyy/MM/dd", "yyyy.MM.dd HH:mm:ss", "yyyy-MM-dd HH:mm" });
        System.out.println("Parsed Date is >>" + parsedDate);
    }//  w  ww  .  j  a v  a2  s.c o  m
    //Display date in HH:mm:ss format
    System.out.println("Now >>" + DateFormatUtils.ISO_TIME_NO_T_FORMAT.format(System.currentTimeMillis()));
}

From source file:eu.cloudwave.wp5.feedbackhandler.aggregations.strategies.SimpleRequestAggregationStrategyImpl.java

/**
 * {@inheritDoc}/*from  w  w w .j  a v a2s  . co m*/
 */
@Override
public RequestAggregationValues aggregate(RequestCollector requests) {

    IntSummaryStatistics stats = requests.getReqTimestamps().stream()
            .collect(Collectors.groupingBy(
                    timestamp -> DateUtils.round(new Date(timestamp), timestampAggregation),
                    Collectors.counting()))
            .values().stream().mapToInt(p -> toInt(p)).summaryStatistics();

    return new RequestAggregationValuesImpl(stats.getMin(), stats.getMax(), stats.getAverage(), stats.getSum(),
            stats.getCount());
}

From source file:eu.cloudwave.wp5.feedbackhandler.repositories.aggregations.AggregatedMicroserviceClientRequest.java

public IntSummaryStatistics getStatistics() {
    // Map<Date, Long> groupedRequests = microserviceClientRequest.getReqTimestamps().stream()
    // .collect(Collectors.groupingBy(timestamp -> DateUtils.round(new Date(timestamp), timestampAggregation),
    // Collectors.counting()));

    return microserviceClientRequest.getReqTimestamps().stream()
            .collect(Collectors.groupingBy(
                    timestamp -> DateUtils.round(new Date(timestamp), timestampAggregation),
                    Collectors.counting()))
            .values().stream().mapToInt(p -> toInt(p)).summaryStatistics();
}

From source file:com.feilong.core.date.DateUtilTest.java

/**
 * Test get last date of this day.//from  w  w  w  .j  av a2  s. c o  m
 */
@Test
public void testGetLastDateOfThisDay() {
    logDate(DateUtil.getLastDateOfThisDay(NOW));
    LOGGER.debug(StringUtils.repeat("*", 20));

    logDate(DateUtils.ceiling(NOW, Calendar.DAY_OF_MONTH));
    logDate(DateUtils.round(NOW, Calendar.DAY_OF_MONTH));
    logDate(DateUtils.truncate(NOW, Calendar.DAY_OF_MONTH));
    LOGGER.debug(StringUtils.repeat("*", 20));
    logDate(DateUtils.ceiling(NOW, Calendar.MONTH));
    logDate(DateUtils.round(NOW, Calendar.MONTH));
    logDate(DateUtils.truncate(NOW, Calendar.MONTH));
}

From source file:eu.cloudwave.wp5.feedbackhandler.aggregations.strategies.RequestAggregationStrategyImpl.java

/**
 * {@inheritDoc}//  www. j a  va 2  s  .  co m
 */
@Override
public RequestAggregationValues aggregate(RequestCollector requests) {
    double expectedCount = getExpectedNumberOfMeasurementValueGroups();

    /*
     * Group by aggregation interval and create summary statistics with min, avg, max and count
     */
    Collection<Long> groupedByAggregationInterval = requests.getReqTimestamps().stream()
            .collect(Collectors.groupingBy(
                    timestamp -> DateUtils.round(new Date(timestamp), timestampAggregation),
                    Collectors.counting()))
            .values();
    int calculatedCount = groupedByAggregationInterval.size();

    try {
        if (calculatedCount != 0) {
            // use integer summaryStatistics to get min, avg, max
            IntSummaryStatistics stats = groupedByAggregationInterval.stream().mapToInt(p -> toInt(p))
                    .summaryStatistics();

            // no time range selected, just return int summary
            if (expectedCount == 0) {
                return new RequestAggregationValuesImpl(stats.getMin(), stats.getMax(), stats.getAverage(),
                        stats.getSum(), stats.getCount());
            } else {
                // if calculated count != expected count --> adjust minimum, average and count value
                if (Double.compare(calculatedCount, expectedCount) != 0) {
                    double newAverage = (double) (stats.getSum() / expectedCount);
                    return new RequestAggregationValuesImpl(0, stats.getMax(), newAverage, stats.getSum(),
                            (int) expectedCount);
                } else {
                    return new RequestAggregationValuesImpl(stats.getMin(), stats.getMax(), stats.getAverage(),
                            stats.getSum(), (int) expectedCount);
                }
            }
        } else {
            return new RequestAggregationValuesImpl(0, 0, 0, 0, 0);
        }
    } catch (ArithmeticException e) {
        System.out.println(e.getMessage());
        return new RequestAggregationValuesImpl(0, 0, 0, 0, 0);
    }
}

From source file:emily.command.administrative.GuildStatsCommand.java

@Override
public String execute(DiscordBot bot, String[] args, MessageChannel channel, User author,
        Message inputMessage) {/*from   w  w  w  .ja va  2s . c om*/
    if (!bot.getContainer().allShardsReady()) {
        return "Not fully loaded yet!";
    }
    if (args.length == 0) {
        return "Statistics! \n" + getTotalTable(bot, false) + "\nYou are on shard # " + bot.getShardId();
    }
    SimpleRank userrank = bot.security.getSimpleRank(author, channel);
    switch (args[0].toLowerCase()) {
    case "mini":
        return "Statistics! \n" + getTotalTable(bot, true);
    case "music":
        return DebugUtil
                .sendToHastebin(getPlayingOn(bot.getContainer(), userrank.isAtLeast(SimpleRank.BOT_ADMIN)
                        || (args.length >= 2 && args[1].equalsIgnoreCase("guilds"))));
    case "activity":
        return lastShardActivity(bot.getContainer());
    case "users":
        if (!(channel instanceof TextChannel)) {
            return Templates.invalid_use.formatGuild(channel);
        }
        TreeMap<Date, Integer> map = new TreeMap<>();
        Guild guild = ((TextChannel) channel).getGuild();
        List<Member> joins = new ArrayList<>(guild.getMembers());
        for (Member join : joins) {
            Date time = DateUtils.round(new Date(join.getJoinDate().toInstant().toEpochMilli()),
                    Calendar.DAY_OF_MONTH);
            if (!map.containsKey(time)) {
                map.put(time, 0);
            }
            map.put(time, map.get(time) + 1);
        }
        List<Date> xData = new ArrayList<>();
        List<Integer> yData = new ArrayList<>();
        int total = 0;
        for (Map.Entry<Date, Integer> entry : map.entrySet()) {
            total += entry.getValue();
            xData.add(entry.getKey());
            yData.add(total);
        }
        XYChart chart = new XYChart(1024, 600);
        chart.setTitle("Users over time for " + guild.getName());
        chart.setXAxisTitle("Date");
        chart.setYAxisTitle("Users");
        chart.getStyler().setTheme(new GGPlot2Theme());
        XYSeries series = chart.addSeries("Users", xData, yData);
        series.setMarker(SeriesMarkers.CIRCLE);
        try {
            File f = new File("./Sample_Chart.png");
            BitmapEncoder.saveBitmap(chart, f.getAbsolutePath(), BitmapEncoder.BitmapFormat.PNG);
            bot.queue.add(channel.sendFile(f), message -> f.delete());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    return "Statistics! \n" + getTotalTable(bot, false);
}

From source file:eu.cloudwave.wp5.feedbackhandler.aggregations.strategies.RequestAggregationStrategyImpl.java

private Long roundDate(Long timestamp) {
    return DateUtils.round(new Date(timestamp), this.timestampAggregation).getTime();
}

From source file:com.sube.daos.mongodb.StatisticDaoTest.java

private void generateUsages() throws InvalidSubeCardException, InvalidProviderException {
    for (int i = 0; i < usagesSize; i++) {
        SubeCardUsage usage = new SubeCardUsage();
        usage.setCard((SubeCard) getRandom(cards));
        Date randomDate = DateUtils.round(
                DateUtils.round(DateUtils.round(getRandomDate(FROM, TO), Calendar.SECOND), Calendar.MINUTE),
                Calendar.HOUR);//w  w  w.  j  a  va  2 s.  co m
        usage.setDatetime(randomDate);
        if ((randomDate.after(TO_DIFF) || DateUtils.isSameDay(randomDate, TO_DIFF))
                && (randomDate.before(TO) || DateUtils.isSameDay(randomDate, TO))) {
            Long count = usages1.get(randomDate);
            if (count != null) {
                count++;
            } else {
                count = Long.valueOf(1l);
            }
            usages1.put(randomDate, count);
        } else if ((randomDate.after(FROM) || DateUtils.isSameDay(randomDate, FROM))
                && (randomDate.before(FROM_DIFF) || DateUtils.isSameDay(randomDate, FROM_DIFF))) {
            Long count = usages2.get(randomDate);
            if (count != null) {
                count++;
            } else {
                count = Long.valueOf(1l);
            }
            usages2.put(randomDate, count);
        }
        if (random.nextInt() % 2 == 0) {
            //Charge Money
            usage.setMoney((random.nextDouble() + 0.1d) * MONEY_LAMBDA); // 3.1
            // max,
            // min
            // 0.1
            usage.setPerformer((Provider) getRandom(cashierProviders));
            cardUsagesDao.chargeMoney(usage);
        } else {
            //Charge Service
            usage.setMoney((random.nextDouble() + 0.1d) * -MONEY_LAMBDA); // -3.1
            // min,
            // max
            // -0.1
            usage.setPerformer((Provider) getRandom(serviceProviders));
            cardUsagesDao.chargeService(usage);
            Long travelsCount = travels.get(usage.getCard());
            if (travelsCount == null) {
                travelsCount = Long.valueOf(1l);
            } else {
                travelsCount++;
            }
            travels.put(usage.getCard(), travelsCount);
        }
        Double totalMoney = usages.get(usage.getPerformer());
        if (totalMoney == null) {
            usages.put(usage.getPerformer(), Math.abs(usage.getMoney()));
        } else {
            totalMoney += Math.abs(usage.getMoney());
            usages.put(usage.getPerformer(), totalMoney);
        }
        registerMoneyExpended(usage);
    }
}

From source file:ezbake.services.search.SSRServiceHandler.java

private Facet getDateRangeFacets(String field, String label) {
    GregorianCalendar calendar = new GregorianCalendar();

    Facet dateFacet = new Facet();
    RangeFacet dateRangeFacet = new RangeFacet();
    BaseFacetValue dateField = new BaseFacetValue();
    dateField.setFacetField(field);/*from   w ww.j  a v  a 2  s . c o  m*/
    dateRangeFacet.setField(dateField);

    FacetRange last24 = new FacetRange(RangeType.DATE);
    calendar.add(Calendar.DAY_OF_YEAR, -1);
    last24hoursMS = DateUtils.round(calendar, Calendar.HOUR).getTimeInMillis();
    last24.setRangeFrom(String.valueOf(last24hoursMS));
    dateRangeFacet.addToRanges(last24);

    FacetRange last48 = new FacetRange(RangeType.DATE);
    calendar.add(Calendar.DAY_OF_YEAR, -1);
    last48hoursMS = DateUtils.round(calendar, Calendar.HOUR).getTimeInMillis();
    last48.setRangeFrom(String.valueOf(last48hoursMS));
    dateRangeFacet.addToRanges(last48);

    FacetRange last72 = new FacetRange(RangeType.DATE);
    calendar.add(Calendar.DAY_OF_YEAR, -1);
    last72hoursMS = DateUtils.round(calendar, Calendar.HOUR).getTimeInMillis();
    last72.setRangeFrom(String.valueOf(last72hoursMS));
    dateRangeFacet.addToRanges(last72);

    FacetRange lastWeek = new FacetRange(RangeType.DATE);
    calendar.add(Calendar.DAY_OF_YEAR, -4);
    last7daysMS = DateUtils.round(calendar, Calendar.HOUR).getTimeInMillis();
    lastWeek.setRangeFrom(String.valueOf(last7daysMS));
    dateRangeFacet.addToRanges(lastWeek);

    FacetRange last30Days = new FacetRange(RangeType.DATE);
    calendar.add(Calendar.DAY_OF_YEAR, -23);
    last30daysMS = DateUtils.round(calendar, Calendar.HOUR).getTimeInMillis();
    last30Days.setRangeFrom(String.valueOf(last30daysMS));
    dateRangeFacet.addToRanges(last30Days);

    FacetRange last90Days = new FacetRange(RangeType.DATE);
    calendar.add(Calendar.DAY_OF_YEAR, -60);
    last90daysMS = DateUtils.round(calendar, Calendar.HOUR).getTimeInMillis();
    last90Days.setRangeFrom(String.valueOf(last90daysMS));
    dateRangeFacet.addToRanges(last90Days);

    FacetRange lastYear = new FacetRange(RangeType.DATE);
    calendar.add(Calendar.DAY_OF_YEAR, -275);
    last365daysMS = DateUtils.round(calendar, Calendar.HOUR).getTimeInMillis();
    lastYear.setRangeFrom(String.valueOf(last365daysMS));
    dateRangeFacet.addToRanges(lastYear);

    FacetRequest dateRequest = new FacetRequest();
    dateRequest.setRangeFacet(dateRangeFacet);

    dateFacet.setLabel(label);
    dateFacet.setFacet(dateRequest);

    return dateFacet;
}

From source file:org.kuali.coeus.common.committee.impl.bo.CommitteeScheduleBase.java

/**
 * This method is BO persistent accessor method, which adds Time to Date on each call. 
 * In support to UI./* www .  ja  v  a2  s.  c om*/
 * @return
 */
public Timestamp getTime() {
    if (this.time != null) {
        java.util.Date dt = new java.util.Date(this.time.getTime());
        dt = DateUtils.round(dt, Calendar.DAY_OF_MONTH);
        if (viewTime != null) {
            dt = new java.util.Date(0); // 12/31/1969 19:00:00
            dt = DateUtils.round(dt, Calendar.DAY_OF_MONTH);
            dt = DateUtils.addMinutes(dt, viewTime.findMinutes()); // to set it to 1970-01-01
            //dt = DateUtils.addMinutes(dt, viewTime.findMinutes());
            //dt = DateUtils.addMinutes(dt, getViewTime().findMinutes());
            this.time = new Timestamp(dt.getTime());
        }
    }
    return time;
}