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

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

Introduction

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

Prototype

public static Date round(Object date, int field) 

Source Link

Document

Round this date, leaving the field specified as the most significant field.

For example, if you had the datetime 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:nl.strohalm.cyclos.utils.DateHelper.java

/**
 * compares two Calendars on a certain precision level. <br>
 * For example, if you had the datetime of 12 Mar 2011 14:31:07.847, and a second datetime of 12 Mar 2011 14:31:11.734, they would evaluate as
 * equal on the Calendar.MINUTE level and above. They would evaluate as not equal on levels Calendar.SECOND and Calendar.MILLISECOND.<br>
 * Fields are rounded, so 12 Mar 2011 14:31:07.847 and 12 Mar 2011 14:31:08.123 would evaluate as equal on the Calendar.SECOND level.
 * @param cal1 if null, returns false//  w w w.  j  av a2s  .  co  m
 * @param cal2 if null, returns false
 * @param level, for example Calendar.MINUTE
 * @return true if equal on this level, false if not.
 */
public static boolean equals(final Calendar cal1, final Calendar cal2, final int level) {
    if (cal1 == null || cal2 == null) {
        return false;
    }
    final Calendar temp1 = DateUtils.round((Calendar) cal1.clone(), level);
    final Calendar temp2 = DateUtils.round((Calendar) cal2.clone(), level);
    return (temp1.equals(temp2));
}

From source file:org.apache.lens.cube.metadata.TestDateUtil.java

@Test
public void testMonthsBetween() throws Exception {
    int i = 0;// w ww.j a v  a  2 s  . c  o m
    assertEquals(getMonthlyCoveringInfo(pairs[i], DateUtils.round(pairs[i + 1], MONTH)),
            new CoveringInfo(1, true), "2013-Jan-01 to 2013-Jan-31");

    i += 2;
    assertEquals(getMonthlyCoveringInfo(pairs[i], DateUtils.round(pairs[i + 1], MONTH)),
            new CoveringInfo(5, true), "2013-Jan-01 to 2013-May-31");

    i += 2;
    assertEquals(getMonthlyCoveringInfo(pairs[i], DateUtils.round(pairs[i + 1], MONTH)),
            new CoveringInfo(12, true), "2013-Jan-01 to 2013-Dec-31");

    i += 2;
    assertEquals(getMonthlyCoveringInfo(pairs[i], pairs[i + 1]), new CoveringInfo(2, false),
            "2013-Feb-01 to 2013-Apr-25");

    i += 2;
    assertEquals(getMonthlyCoveringInfo(pairs[i], pairs[i + 1]), new CoveringInfo(12, true),
            "2012-Feb-01 to 2013-Feb-01");

    i += 2;
    assertEquals(getMonthlyCoveringInfo(pairs[i], pairs[i + 1]), new CoveringInfo(24, true),
            "2011-Feb-01 to 2013-Feb-01");

    i += 2;
    assertEquals(getMonthlyCoveringInfo(pairs[i], pairs[i + 1]), new CoveringInfo(0, false),
            "2013-Jan-02 to 2013-Feb-02");

    i += 2;
    assertEquals(getMonthlyCoveringInfo(pairs[i], pairs[i + 1]), new CoveringInfo(1, false),
            "2013-Jan-02 to 2013-Mar-02");
}

From source file:org.apache.lens.cube.metadata.TestDateUtil.java

@Test
public void testQuartersBetween() throws Exception {
    int i = 0;/*w ww .j  ava 2 s. c o  m*/
    assertEquals(getQuarterlyCoveringInfo(pairs[i], pairs[i + 1]), new CoveringInfo(0, false),
            "2013-Jan-01 to 2013-Jan-31");

    i += 2;
    assertEquals(getQuarterlyCoveringInfo(pairs[i], pairs[i + 1]), new CoveringInfo(1, false),
            "2013-Jan-01 to 2013-May-31");

    i += 2;
    assertEquals(getQuarterlyCoveringInfo(pairs[i], DateUtils.round(pairs[i + 1], MONTH)),
            new CoveringInfo(4, true), "2013-Jan-01 to 2013-Dec-31");

    i += 2;
    assertEquals(getQuarterlyCoveringInfo(pairs[i], pairs[i + 1]), new CoveringInfo(0, false),
            "2013-Feb-01 to 2013-Apr-25");

    i += 2;
    assertEquals(getQuarterlyCoveringInfo(pairs[i], pairs[i + 1]), new CoveringInfo(3, false),
            "2012-Feb-01 to 2013-Feb-01");

    i += 2;
    assertEquals(getQuarterlyCoveringInfo(pairs[i], pairs[i + 1]), new CoveringInfo(7, false),
            "2011-Feb-01 to 2013-Feb-01");
}

From source file:org.apache.lens.cube.metadata.TestDateUtil.java

@Test
public void testYearsBetween() throws Exception {
    int i = 0;/*from  ww  w. j  av a 2s  . c  o  m*/
    assertEquals(getYearlyCoveringInfo(pairs[i], pairs[i + 1]), new CoveringInfo(0, false),
            "" + pairs[i] + "->" + pairs[i + 1]);

    i += 2;
    assertEquals(getYearlyCoveringInfo(pairs[i], pairs[i + 1]), new CoveringInfo(0, false),
            "" + pairs[i] + "->" + pairs[i + 1]);

    i += 2;
    assertEquals(getYearlyCoveringInfo(pairs[i], DateUtils.round(pairs[i + 1], MONTH)),
            new CoveringInfo(1, true), "" + pairs[i] + "->" + pairs[i + 1]);

    i += 2;
    assertEquals(getYearlyCoveringInfo(pairs[i], pairs[i + 1]), new CoveringInfo(0, false),
            "" + pairs[i] + "->" + pairs[i + 1]);

    i += 2;
    assertEquals(getYearlyCoveringInfo(pairs[i], pairs[i + 1]), new CoveringInfo(0, false),
            "" + pairs[i] + "->" + pairs[i + 1]);

    i += 2;
    assertEquals(getYearlyCoveringInfo(pairs[i], pairs[i + 1]), new CoveringInfo(1, false),
            "" + pairs[i] + "->" + pairs[i + 1]);
}

From source file:org.artifactory.traffic.read.TrafficStreamParserTest.java

/**
 * Test the parser with valid in-range dates
 *
 * @throws IOException/* w  w w. java2s  .  c  o  m*/
 * @throws ParseException
 */
public void testWithinRange() throws IOException, ParseException {
    List<String> list = Resources.readLines(trafficLogFile, Charsets.UTF_8);
    String firstEntry = list.get(0);
    String[] splitFirstEntry = firstEntry.split("\\|");
    String lastEntry = list.get(list.size() - 1);
    String[] splitLastEntry = lastEntry.split("\\|");

    Date startDate = entryDateFormat.parse(splitFirstEntry[0]);
    Date endDate = entryDateFormat.parse(splitLastEntry[0]);
    startDate = DateUtils.truncate(startDate, Calendar.MINUTE);
    endDate = DateUtils.round(endDate, Calendar.MINUTE);
    List<TrafficEntry> entries = TrafficStreamParser.parse(new FileReader(trafficLogFile.getFile()), startDate,
            endDate);

    Assert.assertFalse(entries.isEmpty(), "Log parsing should return results.");
    for (TrafficEntry entry : entries) {
        long currentEntryDate = entry.getTime();
        assertTrue(currentEntryDate > startDate.getTime(), "Current entry date should be within range.");
        assertTrue(currentEntryDate < endDate.getTime(), "Current entry date should be within range.");
    }
}

From source file:org.csstudio.swt.widgets.figures.ImageFigure.java

/**
 * start the animation if the image is an animated GIF image.
 *//*from w ww.  jav  a2s  .co  m*/
public synchronized void realStartAnimation() {
    startAnimationRequested = false;
    if (animated && !refreshing && !animationDisabled) {
        repeatCount = loader.repeatCount;
        // animationIndex = 0;
        lastUpdateTime = 0;
        interval_ms = 0;
        refreshing = true;
        Runnable animationTask = new Runnable() {
            public void run() {
                UIBundlingThread.getInstance().addRunnable(new Runnable() {

                    public void run() {
                        synchronized (ImageFigure.this) {
                            if (refreshing && (loader.repeatCount == 0 || repeatCount > 0)) {
                                long currentTime = System.currentTimeMillis();
                                // use Math.abs() to ensure that the system
                                // time adjust won't cause problem
                                if (Math.abs(currentTime - lastUpdateTime) >= interval_ms) {
                                    setShowIndex(animationIndex);
                                    lastUpdateTime = currentTime;
                                    int ms = originalImageDataArray[animationIndex].delayTime * 10;
                                    animationIndex = (animationIndex + 1) % originalImageDataArray.length;
                                    if (ms < 20)
                                        ms += 30;
                                    if (ms < 30)
                                        ms += 10;
                                    interval_ms = ms;
                                    /*
                                     * If we have just drawn the last image,
                                     * decrement the repeat count and start
                                     * again.
                                     */
                                    if (loader.repeatCount > 0
                                            && animationIndex == originalImageDataArray.length - 1)
                                        repeatCount--;
                                }
                            } else if (loader.repeatCount > 0 && repeatCount <= 0) { // stop thread
                                // when
                                // animation
                                // finished
                                if (scheduledFuture != null) {
                                    scheduledFuture.cancel(true);
                                    scheduledFuture = null;
                                }
                            }
                        }

                    }
                });
            }
        };

        if (scheduledFuture != null) {
            scheduledFuture.cancel(true);
            scheduledFuture = null;
        }
        long initialDelay = 100;
        if (alignedToNearestSecond) {
            Date now = new Date();
            DateUtils.round(now, Calendar.SECOND);
            Date nearestSecond = DateUtils.round(now, Calendar.SECOND);
            initialDelay = nearestSecond.getTime() - now.getTime();
            if (initialDelay < 0)
                initialDelay = MILLISEC_IN_SEC + initialDelay;
        }
        scheduledFuture = ExecutionService.getInstance().getScheduledExecutorService()
                .scheduleAtFixedRate(animationTask, initialDelay, 10, TimeUnit.MILLISECONDS);
    }
}

From source file:org.csstudio.swt.widgets.symbol.GIFSymbolImage.java

/**
 * start the animation if the image is an animated GIF image.
 *//*w  ww  .  j  a va2  s  .  com*/
public synchronized void realStartAnimation() {
    startAnimationRequested = false;
    if (animated && !refreshing && !animationDisabled) {
        repeatCount = loader.repeatCount;
        // animationIndex = 0;
        lastUpdateTime = 0;
        interval_ms = 0;
        refreshing = true;
        Runnable animationTask = new Runnable() {
            public void run() {
                UIBundlingThread.getInstance().addRunnable(new Runnable() {

                    public void run() {
                        synchronized (GIFSymbolImage.this) {
                            if (refreshing && (loader.repeatCount == 0 || repeatCount > 0)) {
                                long currentTime = System.currentTimeMillis();
                                // use Math.abs() to ensure that the system
                                // time adjust won't cause problem
                                if (Math.abs(currentTime - lastUpdateTime) >= interval_ms) {
                                    setShowIndex(animationIndex);
                                    lastUpdateTime = currentTime;
                                    int ms = originalImageDataArray[animationIndex].delayTime * 10;
                                    animationIndex = (animationIndex + 1) % originalImageDataArray.length;
                                    if (ms < 20)
                                        ms += 30;
                                    if (ms < 30)
                                        ms += 10;
                                    interval_ms = ms;
                                    /*
                                     * If we have just drawn the last image,
                                     * decrement the repeat count and start
                                     * again.
                                     */
                                    if (loader.repeatCount > 0
                                            && animationIndex == originalImageDataArray.length - 1)
                                        repeatCount--;
                                }
                            } else if (loader.repeatCount > 0 && repeatCount <= 0) {
                                // stop thread when animation finished
                                if (scheduledFuture != null) {
                                    scheduledFuture.cancel(true);
                                    scheduledFuture = null;
                                }
                            }
                        }
                    }
                });
            }
        };
        if (scheduledFuture != null) {
            scheduledFuture.cancel(true);
            scheduledFuture = null;
        }
        long initialDelay = 100;
        if (alignedToNearestSecond) {
            Date now = new Date();
            DateUtils.round(now, Calendar.SECOND);
            Date nearestSecond = DateUtils.round(now, Calendar.SECOND);
            initialDelay = nearestSecond.getTime() - now.getTime();
            if (initialDelay < 0)
                initialDelay = MILLISEC_IN_SEC + initialDelay;
        }
        scheduledFuture = ExecutionService.getInstance().getScheduledExecutorService()
                .scheduleAtFixedRate(animationTask, initialDelay, 10, TimeUnit.MILLISECONDS);
    }
}

From source file:org.csstudio.utility.batik.AnimatedSVGCache.java

/**
 * Notify images in the same order & time interval as received.
 *///from w  w  w. j  a  va 2s .c o  m
public void startProcessing() {
    if (entries.size() == 0) {
        return;
    }
    Runnable animationTask = new Runnable() {
        private long lastUpdateTime = 0;
        private int currentIndex = 0;

        public void run() {
            long currentTime = System.currentTimeMillis();
            Entry currentEntry = entries.get(currentIndex);
            // use Math.abs() to ensure that the system
            // time adjust won't cause problem
            if (Math.abs(currentTime - lastUpdateTime) >= currentEntry.getWaitTime()) {
                if (listener != null) {
                    listener.newImage(currentEntry.getImage());
                }
                currentIndex++;
                if (currentIndex >= entries.size()) {
                    currentIndex = 0;
                }
                lastUpdateTime = currentTime;
            }
        }
    };
    if (scheduledMain != null) {
        scheduledMain.cancel(true);
        scheduledMain = null;
    }
    running = false;
    long initialDelay = 100;
    if (alignedToNearestSecond) {
        Date now = new Date();
        Date nearestSecond = DateUtils.round(now, Calendar.SECOND);
        initialDelay = nearestSecond.getTime() - now.getTime();
        if (initialDelay < 0) {
            initialDelay += 1000; // number of milliseconds in 1 seconds
        }
    }
    scheduledMain = ExecutionService.getInstance().getScheduledExecutorService()
            .scheduleAtFixedRate(animationTask, initialDelay, 10, TimeUnit.MILLISECONDS);
    running = true;
}

From source file:org.csstudio.utility.batik.SVGHandler.java

private void alignTimeToNearestSecond() {
    Runnable startTask = new Runnable() {
        public void run() {
            if (disposed) {
                return;
            }/* w  w  w .j a v a  2 s  .  com*/
            Date now = new Date();
            Date nearestSecond = DateUtils.round(now, Calendar.SECOND);
            long initialDelay = nearestSecond.getTime() - now.getTime();
            if (initialDelay < 0) {
                initialDelay = MILLISEC_IN_SEC + initialDelay;
            }
            try {
                Thread.sleep(initialDelay);
            } catch (InterruptedException e) {
                Activator.getLogger().log(Level.WARNING, "SVG animation FAILED to align to nearest second");
            }
            resetDocumentTime();
            // restart/reset cache
            if (useCache && cache.isRunning()) {
                cache.restartProcessing();
            }
        }
    };
    new Thread(startTask).start();
}

From source file:org.csstudio.utility.batik.SVGHandler.java

/**
 * Start the processing of the current document.
 *///  w w w. ja  v a 2s. com
public void startProcessing() {
    if (disposed) {
        return;
    }
    if (started) {
        resumeProcessing();
        return;
    }
    if (needRender) {
        doRender();
    }
    Runnable startTask = new Runnable() {
        public void run() {
            try {
                if (disposed) {
                    return;
                }
                updateManager = new UpdateManager(bridgeContext, gvtRoot, svgDocument);
                updateManager.addUpdateManagerListener(listener);
                updateManager.manageUpdates(renderer);
                svgAnimationEngine = (SVGAnimationEngine) bridgeContext.getAnimationEngine();
                timedDocumentRoot = svgAnimationEngine.getTimedDocumentRoot();
                if (useCache) {
                    resetCache();
                }
                long initialDelay = 0;
                if (alignedToNearestSecond) {
                    Date now = new Date();
                    Date nearestSecond = DateUtils.round(now, Calendar.SECOND);
                    initialDelay = nearestSecond.getTime() - now.getTime();
                    if (initialDelay < 0) {
                        initialDelay = MILLISEC_IN_SEC + initialDelay;
                    }
                }
                try {
                    Thread.sleep(initialDelay);
                } catch (InterruptedException e) {
                    Activator.getLogger().log(Level.WARNING, "SVG animation FAILED to align to nearest second");
                }
                // This will call SVGAnimationEngine.start(long documentStartTime)
                // with System.currentTimeMillis()
                updateManager.dispatchSVGLoadEvent();
                started = true;
                suspended = false;
                Activator.getLogger().log(Level.FINE, "SVG animation STARTED");
            } catch (Exception e) {
                handleException(e);
                return;
            } catch (OutOfMemoryError e) {
                Activator.getLogger().log(Level.SEVERE, "ERROR starting SVG animation: " + e.getMessage());
                return;
            }
        }
    };
    new Thread(startTask).start();
}