How to calculate the difference between two Java java.sql.Timestamps? - java

Please include the nanos, otherwise it would be trivial:
long diff = Math.abs(t1.getTime () - t2.getTime ());
[EDIT] I want the most precise result, so no doubles; only integer/long arithmetic. Also, the result must be positive. Pseudo code:
Timestamp result = abs (t1 - t2);
Examples:
t1 = (time=1001, nanos=1000000), t2 = (time=999, nanos=999000000)
-> diff = (time=2, nanos=2000000)
Yes, milliseconds in java.sql.Timestamp are duplicated in the time and the nanos par, so 1001 milliseconds means 1 second (1000) and 1 milli which is in the time part and the nanos part because 1 millisecond = 1000000 nanoseconds). This is much more devious than it looks.
I suggest not to post an answer without actually testing the code or having a working code sample ready :)

After one hour and various unit tests, I came up with this solution:
public static Timestamp diff (java.util.Date t1, java.util.Date t2)
{
// Make sure the result is always > 0
if (t1.compareTo (t2) < 0)
{
java.util.Date tmp = t1;
t1 = t2;
t2 = tmp;
}
// Timestamps mix milli and nanoseconds in the API, so we have to separate the two
long diffSeconds = (t1.getTime () / 1000) - (t2.getTime () / 1000);
// For normals dates, we have millisecond precision
int nano1 = ((int) t1.getTime () % 1000) * 1000000;
// If the parameter is a Timestamp, we have additional precision in nanoseconds
if (t1 instanceof Timestamp)
nano1 = ((Timestamp)t1).getNanos ();
int nano2 = ((int) t2.getTime () % 1000) * 1000000;
if (t2 instanceof Timestamp)
nano2 = ((Timestamp)t2).getNanos ();
int diffNanos = nano1 - nano2;
if (diffNanos < 0)
{
// Borrow one second
diffSeconds --;
diffNanos += 1000000000;
}
// mix nanos and millis again
Timestamp result = new Timestamp ((diffSeconds * 1000) + (diffNanos / 1000000));
// setNanos() with a value of in the millisecond range doesn't affect the value of the time field
// while milliseconds in the time field will modify nanos! Damn, this API is a *mess*
result.setNanos (diffNanos);
return result;
}
Unit tests:
Timestamp t1 = new Timestamp (0);
Timestamp t3 = new Timestamp (999);
Timestamp t4 = new Timestamp (5001);
// Careful here; internally, Java has set nanos already!
t4.setNanos (t4.getNanos () + 1);
// Show what a mess this API is...
// Yes, the milliseconds show up in *both* fields! Isn't that fun?
assertEquals (999, t3.getTime ());
assertEquals (999000000, t3.getNanos ());
// This looks weird but t4 contains 5 seconds, 1 milli, 1 nano.
// The lone milli is in both results ...
assertEquals (5001, t4.getTime ());
assertEquals (1000001, t4.getNanos ());
diff = DBUtil.diff (t1, t4);
assertEquals (5001, diff.getTime ());
assertEquals (1000001, diff.getNanos ());
diff = DBUtil.diff (t4, t3);
assertEquals (4002, diff.getTime ());
assertEquals (2000001, diff.getNanos ());

I use this method to get difference between 2 java.sql.Timestmap
/**
* Get a diff between two timestamps.
*
* #param oldTs The older timestamp
* #param newTs The newer timestamp
* #param timeUnit The unit in which you want the diff
* #return The diff value, in the provided time unit.
*/
public static long getDateDiff(Timestamp oldTs, Timestamp newTs, TimeUnit timeUnit) {
long diffInMS = newTs.getTime() - oldTs.getTime();
return timeUnit.convert(diffInMS, TimeUnit.MILLISECONDS);
}
// Examples:
// long diffMinutes = getDateDiff(oldTs, newTs, TimeUnit.MINUTES);
// long diffHours = getDateDiff(oldTs, newTs, TimeUnit.HOURS);

In what units? your diff above will give milliseconds, Timestamp.nanos() returns an int, which would be in (millionths?) of a millisecond.So do you mean e.g.
(t1.getTime () + (.000001*t1.getNanos()) - (t2.getTime () + (.000001*t2.getNanos())
or am I missing something? Another question is do you need this level of precision? AFAIK the JVM isn't guaranteed to be precise at this level, I don't think it'd matter unless you're sure your datasource is that precise.

Building on mmyers code...
import java.math.BigInteger;
import java.sql.Timestamp;
public class Main
{
// 1s == 1000ms == 1,000,000us == 1,000,000,000ns (1 billion ns)
public final static BigInteger ONE_BILLION = new BigInteger ("1000000000");
public static void main(String[] args) throws InterruptedException
{
final Timestamp t1;
final Timestamp t2;
final BigInteger firstTime;
final BigInteger secondTime;
final BigInteger diffTime;
t1 = new Timestamp(System.currentTimeMillis());
Thread.sleep(20);
t2 = new Timestamp(System.currentTimeMillis());
System.out.println(t1);
System.out.println(t2);
firstTime = BigInteger.valueOf(t1.getTime() / 1000 * 1000).multiply(ONE_BILLION ).add(BigInteger.valueOf(t1.getNanos()));
secondTime = BigInteger.valueOf(t2.getTime() / 1000 * 1000).multiply(ONE_BILLION ).add(BigInteger.valueOf(t2.getNanos()));
diffTime = firstTime.subtract(secondTime);
System.out.println(firstTime);
System.out.println(secondTime);
System.out.println(diffTime);
}
}

(old code removed to shorten answer)
EDIT 2: New code:
public class ArraySizeTest {
public static void main(String[] args) throws InterruptedException {
Timestamp t1 = new Timestamp(System.currentTimeMillis());
t1.setNanos(t1.getNanos() + 60);
Thread.sleep(20);
Timestamp t2 = new Timestamp(System.currentTimeMillis());
t2.setNanos(t2.getNanos() + 30);
System.out.println(t1);
System.out.println(t2);
// The actual diff...
long firstTime = (getTimeNoMillis(t1) * 1000000) + t1.getNanos();
long secondTime = (getTimeNoMillis(t2) * 1000000) + t2.getNanos();
long diff = Math.abs(firstTime - secondTime); // diff is in nanos
System.out.println(diff);
System.out.println(Math.abs(t1.getTime() - t2.getTime()));
}
private static long getTimeNoMillis(Timestamp t) {
return t.getTime() - (t.getNanos()/1000000);
}
}
Output:
2009-02-24 10:35:15.56500006
2009-02-24 10:35:15.59600003
30999970
31
Edit 3: If you'd prefer something that returns a Timestamp, use this:
public static Timestamp diff(Timestamp t1, Timestamp t2) {
long firstTime = (getTimeNoMillis(t1) * 1000000) + t1.getNanos();
long secondTime = (getTimeNoMillis(t2) * 1000000) + t2.getNanos();
long diff = Math.abs(firstTime - secondTime); // diff is in nanoseconds
Timestamp ret = new Timestamp(diff / 1000000);
ret.setNanos((int) (diff % 1000000000));
return ret;
}
private static long getTimeNoMillis(Timestamp t) {
return t.getTime() - (t.getNanos()/1000000);
}
This code passes your unit tests.

Related

How can I count the number of events in a given interval?

I need to know how frequency different events occur. For example how many HTTP requests have occurred in the last 15 minutes. Because there can be a large count of events (millions) this must be use a limited amount of memory.
It there any util class in Java that can do this?
How can I implement this self in Java?
Theoretical usage code can look like:
FrequencyCounter counter = new FrequencyCounter( 15, TimeUnit.Minutes );
...
counter.add();
...
int count = counter.getCount();
Edit: It must be a real time value which can changed thousand times the minute and will be query thousands times the minute. That a database or file based solution are not possible.
Here is my implementation of such a counter. The memory usage with the default precision is fewer as 100 bytes. The memory usage is independent of the event count.
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A counter that counts events within the past time interval. All events that occurred before this interval will be
* removed from the counter.
*/
public class FrequencyCounter {
private final long monitoringInterval;
private final int[] details;
private final AtomicInteger currentCount = new AtomicInteger();
private long startInterval;
private int total;
/**
* Create a new instance of the counter for the given interval.
*
* #param interval the time to monitor/count the events.
* #param unit the time unit of the {#code interval} argument
*/
FrequencyCounter( long interval, TimeUnit unit ) {
this( interval, unit, 16 );
}
/**
* Create a new instance of the counter for the given interval.
*
* #param interval the time to monitor/count the events.
* #param unit the time unit of the {#code interval} argument
* #param precision the count of time slices for the for the measurement
*/
FrequencyCounter( long interval, TimeUnit unit, int precision ) {
monitoringInterval = unit.toMillis( interval );
if( monitoringInterval <= 0 ) {
throw new IllegalArgumentException( "Interval mus be a positive value:" + interval );
}
details = new int[precision];
startInterval = System.currentTimeMillis() - monitoringInterval;
}
/**
* Count a single event.
*/
public void increment() {
checkInterval( System.currentTimeMillis() );
currentCount.incrementAndGet();
}
/**
* Get the current value of the counter.
*
* #return the counter value
*/
public int getCount() {
long currentTime = System.currentTimeMillis();
checkInterval( currentTime );
long diff = currentTime - startInterval - monitoringInterval;
double partFactor = (diff * details.length / (double)monitoringInterval);
int part = (int)(details[0] * partFactor);
return total + currentCount.get() - part;
}
/**
* Check the interval of the detail counters and move the interval if needed.
*
* #param time the current time
*/
private void checkInterval( final long time ) {
if( (time - startInterval - monitoringInterval) > monitoringInterval / details.length ) {
synchronized( details ) {
long detailInterval = monitoringInterval / details.length;
while( (time - startInterval - monitoringInterval) > detailInterval ) {
int currentValue = currentCount.getAndSet( 0 );
if( (total | currentValue) == 0 ) {
// for the case that the counter was not used for a long time
startInterval = time - monitoringInterval;
return;
}
int size = details.length - 1;
total += currentValue - details[0];
System.arraycopy( details, 1, details, 0, size );
details[size] = currentValue;
startInterval += detailInterval;
}
}
}
}
}
The best way I can think to implement this is using another "time counting" thread.
If you're concerned about the amount of memory, you can add a threshold for the size of eventsCounter (Integer.MAX_VALUE seems like the natural choice).
Here's an example for an implementation, that is also thread-safe:
public class FrequencyCounter {
private AtomicInteger eventsCounter = new AtomicInteger(0);
private int timeCounter;
private boolean active;
public FrequencyCounter(int timeInSeconds) {
timeCounter = timeInSeconds;
active = true;
}
// Call this method whenever an interesting event occurs
public int add() {
if(active) {
int current;
do {
current = eventsCounter.get();
} while (eventsCounter.compareAndSet(current, current + 1));
return current + 1;
}
else return -1;
}
// Get current number of events
public int getCount() {
return eventsCounter.get();
}
// Start the FrequencyCounter
public void run() {
Thread timer = new Thread(() -> {
while(timeCounter > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
timeCounter --;
}
active = false;
});
timer.start();
}
}
How about a scheduled executor service.
class TimedValue{
int startValue;
int finishedValue;
TimedValue(int start){
startValue = start;
}
}
List<TimedValue> intervals = new CopyOnWriteArrayList<>();
//then when starting a measurement.
TimeValue value = new TimedValue();
//set the start value.
Callable<TimedValue> callable = ()->{
//performs the task.
value.setValueAtFinish(getCount());
return value;
}
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
ScheduledFuture<TimedValue> future = executor.schedule(
callable,
TimeUnit.MINUTES,
15);
executor.schedule(()->itervals.add(
future.get(),
TimeUnit.MINUTES,
future.getDelay(TimeUnit.MINUTES
);
This is a bit of a complicated method.
I would probably just have a List<LoggedValues> and accumulate values in that list at a fixed rate. Then it could be inspected whenever you want to know an intervals.

Java cooldown system

I've been trying to make a cooldown system in java given three variables,
the cooldown time, for example 100 seconds,
the click timestamp(when it was last clicked)
the current timestamp.
I made it work before but it looks very complicated, I was wondering if there is a better way to do it.
My code to check if the click is on cooldown or not:
private boolean onCooldown(String playerUUID, int npcId, int cooldown) {
boolean toReturn = false;
try {
String timeStamp = new SimpleDateFormat("yyyy/MM/dd_HH:mm:ss").format(Calendar.getInstance().getTime());
DateFormat df = new SimpleDateFormat("yyyy/MM/dd_HH:mm:ss");
Date savedTime;
Date nowTime;
String savedString = database.getTime(playerUUID, npcId);
nowTime = df.parse(timeStamp);
savedTime = df.parse(savedString);
long diff = nowTime.getTime() - savedTime.getTime();
long savedSeconds = diff / 1000 % 60;
long savedMinutes = diff / (60 * 1000) % 60;
long nowSeconds = cooldown % 60;
long nowMinutes = cooldown / 60 % 60;
if (!((savedMinutes >= nowMinutes) && (savedSeconds >= nowSeconds))) {
toReturn = true;
}
} catch (Exception e) {
toReturn = false;
}
return toReturn;
}
Is there a better or easier way than this?
Cheers.
I'd recommend using a HashMap that stores the player's UUID and the current timestamp. Within the method you can then check if the map contains the player's key and if so check if the value stored and your desired cooldown is less/greater than the current time.
As Craigr8806 stated in the comments, I'd recommend using System.nanoTime() for the timestamps.

How to correct calculate the running time

I want to calculate the total running time of my program from start to end and refresh running time in JFrame, but when I run my program I get excess 70 years, 1 day and 2 hours. Why ? What wrong ?
private void setMachineTime(){
Timer timer = new Timer();
long startTime = new Date().getTime();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
long endTime = new Date().getTime();
long diffTime = endTime - startTime ;
String time = new SimpleDateFormat("yy:mm:dd:HH:mm:ss").format(diffTime);
System.out.println(time);
}
}, 0, 1000);
}
actual result
UPD:
I rewrote code with my own format time method. Now I got what I want. Thanks to all of you.
private void setMachineTime(){
Timer timer = new Timer();
long startTime = new Date().getTime();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
long endTime = new Date().getTime();
long diffTime = endTime - startTime;
String diffSeconds = formatTime(diffTime / 1000 % 60);
String diffMinutes = formatTime(diffTime / (60 * 1000) % 60);
String diffHours = formatTime(diffTime / (60 * 60 * 1000) % 24);
System.out.println(diffHours + ":" + diffMinutes + ":" + diffSeconds);
}
}, 0, 1000);
}
private String formatTime(long diff){
long t;
t = diff;
if(t < 10){
return String.valueOf("0"+t);
} else {
return String.valueOf(t);
}
}
You are formatting the time difference as yy:mm:dd:HH:mm:ss. Just printing out diffTime would give you the milliseconds, divide by 1000 if you need seconds.
EDIT: I think i see what you are trying to do, but you are dealing with a time interval, which cannot be formatted as a date. You'll need to roll your own formatting for displaying the time as seconds, minutes, hours etc. or use an external library.
getTime return number of milliseconds from 1.1.1970...and same is for SimpleDateFormat converting number to date (and then formating it). It means when your diffTime = 0, SimpleDateFormat will try to format Date 1.1.1970 0:00:00 and with your formating string it will be 70:01:01:00:00:00. Try to use http://joda-time.sourceforge.net/api-release/org/joda/time/Interval.html instead.
And by the way, your formating string is wrong anyway...you use mm where I supouse you wanted month...but mm are minutes.

Find missing date ranges in timeline using java

I have a custom java sync that fetch data by date range thoght SOAP service running on tomcat.
Ex:
getDataByDateRange(startDate,endDate)
getDataByDateRange('2016-01-01 10:00:00.00000','2016-01-01 11:00:00.00000')
I want to write a control program to check if any range has been missed by any kind of runtime or server error.
How can I find the missing date ranges?
Thanks.
Visually Example:
TimeLine : [------------------------------------------------------------------]
Processed Dates: [----1---][---2----]---[-3-][--4---]---[----5---][---6--]-----------
Missing Dates : -------------------[-1-]-----------[-2-]----------------[-----3----]
TimeLine:
1: '2016-01-01 10:00:00.00000','2016-02-01 09:00:00.00000'
Processed Dates:
1: '2016-01-01 10:00:00.00000','2016-01-01 11:00:00.00000'
2: '2016-01-01 11:00:00.00000','2016-01-01 12:00:00.00000'
3: '2016-01-01 13:00:00.00000','2016-01-01 13:30:00.00000'
4: '2016-01-01 13:30:00.00000','2016-01-01 14:30:00.00000'
5: '2016-01-01 15:30:00.00000','2016-01-01 16:30:00.00000'
6: '2016-01-01 16:30:00.00000','2016-01-01 17:00:00.00000'
Missing Dates:
1: '2016-01-01 12:00:00.00000','2016-01-01 13:00:00.00000'
2: '2016-01-01 14:30:00.00000','2016-01-01 15:30:00.00000'
3: '2016-01-01 17:00:00.00000','2016-01-02 09:00:00.00000'
According to your comment I post my previous comment as answer. This solution uses my library Time4J (including the range-module):
// prepare parser
ChronoFormatter<PlainTimestamp> f =
ChronoFormatter.ofTimestampPattern( // five decimal digits
"uuuu-MM-dd HH:mm:ss.SSSSS", PatternType.CLDR, Locale.ROOT);
// parse input to intervals - here the overall time window
TimestampInterval timeline =
TimestampInterval.between(
f.parse("2016-01-01 10:00:00.00000"),
f.parse("2016-02-01 09:00:00.00000"));
// for more flexibility - consider a for-each-loop
TimestampInterval i1 =
TimestampInterval.between(f.parse("2016-01-01 10:00:00.00000"), f.parse("2016-01-01 11:00:00.00000"));
TimestampInterval i2 =
TimestampInterval.between(f.parse("2016-01-01 11:00:00.00000"), f.parse("2016-01-01 12:00:00.00000"));
TimestampInterval i3 =
TimestampInterval.between(f.parse("2016-01-01 13:00:00.00000"), f.parse("2016-01-01 13:30:00.00000"));
TimestampInterval i4 =
TimestampInterval.between(f.parse("2016-01-01 13:30:00.00000"), f.parse("2016-01-01 14:30:00.00000"));
TimestampInterval i5 =
TimestampInterval.between(f.parse("2016-01-01 15:30:00.00000"), f.parse("2016-01-01 16:30:00.00000"));
TimestampInterval i6 =
TimestampInterval.between(f.parse("2016-01-01 16:30:00.00000"), f.parse("2016-01-01 17:00:00.00000"));
// apply interval arithmetic
IntervalCollection<PlainTimestamp> icoll =
IntervalCollection.onTimestampAxis().plus(Arrays.asList(i1, i2, i3, i4, i5, i6));
List<ChronoInterval<PlainTimestamp>> missed = icoll.withComplement(timeline).getIntervals();
// result
System.out.println(missed);
// [[2016-01-01T12/2016-01-01T13), [2016-01-01T14:30/2016-01-01T15:30), [2016-01-01T17/2016-02-01T09)]
The core of the whole interval arithmetic is just done by the code fragment icoll.withComplement(timeline). The rest is only about creation of intervals. By applying a for-each-loop you can surely minimize again the count of lines in presented code.
The output is based on the canonical description of the intervals implicitly using toString(), for example: [2016-01-01T12/2016-01-01T13) The square bracket denotes a closed boundary while the round bracket to the right end denotes an open boundary. So we have here the standard case of half-open timestamp intervals (without timezone). While other interval types are possible I have chosen that type because it corresponds to the type of your input strings.
If you plan to combine this solution with Joda-Time in other parts of your app then keep in mind that a) there is not yet any special bridge between both libraries available and b) the conversion looses microsecond precision (Joda-Time only supports milliseconds) and c) Time4J has much more power than Joda-Time (for almost everything). Anyway, you can do this as conversion (important if you don't want to do the effort of bigger rewriting of your app):
ChronoInterval<PlainTimestamp> missed0 = missed.get(0);
PlainTimestamp tsp = missed0.getStart().getTemporal();
LocalDateTime ldt = // joda-equivalent
new LocalDateTime(
tsp.getYear(), tsp.getMonth(), tsp.getDayOfMonth(),
tsp.getHour(), tsp.getMinute(), tsp.getSecond(), tsp.get(PlainTime.MILLI_OF_SECOND));
System.out.println(ldt); // 2016-01-01T10:00:00.000
About a Joda-only solution:
Joda-Time does only support instant intervals, not timestamp intervals without timezone. However, you could simulate that missing interval type by hardwiring the timezone to UTC (using fixed offset).
Another problem is missing support for five decimal digits. You can circumvent it by this hack:
DateTime start =
DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS")
.withZoneUTC()
.parseDateTime("2016-01-01 16:30:00.00000".substring(0, 23));
System.out.println(start); // 2016-01-01T16:30:00.000Z
DateTime end = ...;
Interval interval = new Interval(start, end);
The other more critical element of a solution is almost missing - interval arithmetic. You have to sort the intervals first by start instant (and then by end instant). After sorting, you can iterate over all intervals such that you find the gaps. The best thing Joda-Time can do for you here is giving you methods like isBefore(anotherInstant) etc. which you can use in your own solution. But it gets pretty much bloated.
Given that the frequency of date ranges is one hour, you can start with range start date, iterate till range end date and write a method that checks for an entry with dates. You can use DateUtils to add hour to date, as shown in the below pseudo code:
Date startDate = startDate;
Date endDate = endDate;
while (startDate.before(endDate){
if(!exists(startDate, DateUtils.addHours(startDate, 1), entries)){
//Add into missing entries
}
startDate = DateUtils.addHours(startDate, 1);
}
I posted my IntervalTree a while ago - it seems to work well with this kind of problem.
See the minimise method for what you are looking for.
/**
* Title: IntervlTree
*
* Description: Implements a static Interval Tree. i.e. adding and removal are not possible.
*
* This implementation uses longs to bound the intervals but could just as easily use doubles or any other linear value.
*
* #author OldCurmudgeon
* #version 1.0
* #param <T> - The Intervals to work with.
*/
public class IntervalTree<T extends IntervalTree.Interval> {
// My intervals.
private final List<T> intervals;
// My center value. All my intervals contain this center.
private final long center;
// My interval range.
private final long lBound;
private final long uBound;
// My left tree. All intervals that end below my center.
private final IntervalTree<T> left;
// My right tree. All intervals that start above my center.
private final IntervalTree<T> right;
public IntervalTree(List<T> intervals) {
if (intervals == null) {
throw new NullPointerException();
}
// Initially, my root contains all intervals.
this.intervals = intervals;
// Find my center.
center = findCenter();
/*
* Builds lefts out of all intervals that end below my center.
* Builds rights out of all intervals that start above my center.
* What remains contains all the intervals that contain my center.
*/
// Lefts contains all intervals that end below my center point.
final List<T> lefts = new ArrayList<>();
// Rights contains all intervals that start above my center point.
final List<T> rights = new ArrayList<>();
long uB = Long.MIN_VALUE;
long lB = Long.MAX_VALUE;
for (T i : intervals) {
long start = i.getStart();
long end = i.getEnd();
if (end < center) {
lefts.add(i);
} else if (start > center) {
rights.add(i);
} else {
// One of mine.
lB = Math.min(lB, start);
uB = Math.max(uB, end);
}
}
// Remove all those not mine.
intervals.removeAll(lefts);
intervals.removeAll(rights);
uBound = uB;
lBound = lB;
// Build the subtrees.
left = lefts.size() > 0 ? new IntervalTree<>(lefts) : null;
right = rights.size() > 0 ? new IntervalTree<>(rights) : null;
// Build my ascending and descending arrays.
/**
* #todo Build my ascending and descending arrays.
*/
}
/*
* Returns a list of all intervals containing the point.
*/
List<T> query(long point) {
// Check my range.
if (point >= lBound) {
if (point <= uBound) {
// Gather all intersecting ones.
List<T> found = intervals
.stream()
.filter((i) -> (i.getStart() <= point && point <= i.getEnd()))
.collect(Collectors.toList());
// Gather others.
if (point < center && left != null) {
found.addAll(left.query(point));
}
if (point > center && right != null) {
found.addAll(right.query(point));
}
return found;
} else {
// To right.
return right != null ? right.query(point) : Collections.<T>emptyList();
}
} else {
// To left.
return left != null ? left.query(point) : Collections.<T>emptyList();
}
}
/**
* Blends the two lists together.
*
* If the ends touch then make them one.
*
* #param a
* #param b
* #return
*/
static List<Interval> blend(List<Interval> a, List<Interval> b) {
// Either empty - return the other.
if (a.isEmpty()) {
return b;
}
if (b.isEmpty()) {
return a;
}
// Where does a end and b start.
Interval aEnd = a.get(a.size() - 1);
Interval bStart = b.get(0);
ArrayList<Interval> blended = new ArrayList<>();
// Do they meet/cross?
if (aEnd.getEnd() >= bStart.getStart() - 1) {
// Yes! merge them.
// Remove the last.
blended.addAll(a.subList(0, a.size() - 1));
// Add a combined one.
blended.add(new SimpleInterval(aEnd.getStart(), bStart.getEnd()));
// Add all but the first.
blended.addAll(b.subList(1, b.size()));
} else {
// Just join them.
blended.addAll(a);
blended.addAll(b);
}
return blended;
}
static List<Interval> blend(List<Interval> a, List<Interval> b, List<Interval>... more) {
List<Interval> blended = blend(a, b);
for (List<Interval> l : more) {
blended = blend(blended, l);
}
return blended;
}
List<Interval> minimise() {
// Calculate min of left and right.
List<Interval> minLeft = left != null ? left.minimise() : Collections.EMPTY_LIST;
List<Interval> minRight = right != null ? right.minimise() : Collections.EMPTY_LIST;
// My contribution.
long meLeft = minLeft.isEmpty() ? lBound : Math.max(lBound, minLeft.get(minLeft.size() - 1).getEnd());
long meRight = minRight.isEmpty() ? uBound : Math.min(uBound, minRight.get(0).getEnd());
return blend(minLeft,
Collections.singletonList(new SimpleInterval(meLeft, meRight)),
minRight);
}
private long findCenter() {
//return average();
return median();
}
protected long median() {
if (intervals.isEmpty()) {
return 0;
}
// Choose the median of all centers. Could choose just ends etc or anything.
long[] points = new long[intervals.size()];
int x = 0;
for (T i : intervals) {
// Take the mid point.
points[x++] = (i.getStart() + i.getEnd()) / 2;
}
Arrays.sort(points);
return points[points.length / 2];
}
/*
* What an interval looks like.
*/
public interface Interval {
public long getStart();
public long getEnd();
}
/*
* A simple implemementation of an interval.
*/
public static class SimpleInterval implements Interval {
private final long start;
private final long end;
public SimpleInterval(long start, long end) {
this.start = start;
this.end = end;
}
#Override
public long getStart() {
return start;
}
#Override
public long getEnd() {
return end;
}
#Override
public String toString() {
return "{" + start + "," + end + "}";
}
}
/**
* Not called by App, so you will have to call this directly.
*
* #param args
*/
public static void main(String[] args) {
/**
* #todo Needs MUCH more rigorous testing.
*/
// Test data.
long[][] data = {
{1, 4}, {2, 5}, {5, 7}, {10, 11}, {13, 20}, {19, 21},};
List<Interval> intervals = new ArrayList<>();
for (long[] pair : data) {
intervals.add(new SimpleInterval(pair[0], pair[1]));
}
// Build it.
IntervalTree<Interval> test = new IntervalTree<>(intervals);
// Test it.
System.out.println("Normal test: ---");
for (long i = 0; i < 10; i++) {
List<Interval> intersects = test.query(i);
System.out.println("Point " + i + " intersects:");
intersects.stream().forEach((t) -> {
System.out.println(t.toString());
});
}
// Check minimise.
List<Interval> min = test.minimise();
System.out.println("Minimise test: ---");
System.out.println(min);
// Check for empty list.
intervals.clear();
test = new IntervalTree<>(intervals);
// Test it.
System.out.println("Empty test: ---");
for (long i = 0; i < 10; i++) {
List<Interval> intersects = test.query(i);
System.out.println("Point " + i + " intersects:");
intersects.stream().forEach((t) -> {
System.out.println(t.toString());
});
}
}
}
This gets close to what you are looking for. Here's some code to minimise your ranges into just 3.
static String[][] dates = {{"2016-01-01 10:00:00.00000", "2016-01-01 11:00:00.00000"}, {"2016-01-01 11:00:00.00000", "2016-01-01 12:00:00.00000"}, {"2016-01-01 13:00:00.00000", "2016-01-01 13:30:00.00000"}, {"2016-01-01 13:30:00.00000", "2016-01-01 14:30:00.00000"}, {"2016-01-01 15:30:00.00000", "2016-01-01 16:30:00.00000"}, {"2016-01-01 16:30:00.00000", "2016-01-01 17:00:00.00000"}};
static List<IntervalTree.SimpleInterval> ranges = new ArrayList<>();
static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
static {
for (String[] pair : dates) {
try {
ranges.add(new IntervalTree.SimpleInterval(df.parse(pair[0]).getTime(), df.parse(pair[1]).getTime()));
} catch (ParseException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void test() {
IntervalTree tree = new IntervalTree<>(ranges);
List<IntervalTree.Interval> min = tree.minimise();
//System.out.println("min->" + min);
for (IntervalTree.Interval i : min) {
System.out.println(df.format(new Date(i.getStart())) + " - " + df.format(new Date(i.getEnd())));
}
}
which prints
2016-01-01 10:00:00.0 - 2016-01-01 12:00:00.0
2016-01-01 13:00:00.0 - 2016-01-01 14:30:00.0
2016-01-01 15:30:00.0 - 2016-01-01 17:00:00.0
which is all of your Processed Dates joined into three date ranges.

Converting date into text format

How do I convert date into its text format..for ex:if updated today..then instead of date it must show "Today",one day after it must show "Yesterday",and then after two days..it must display the date in general form(//_) on which it was updated..i tried using SimpleDateFormat..but not working..
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date d= new Date();
//Convert Date object to string
String strDate = sdf.format(d);
System.out.println("Formated String is " + strDate);
d = sdf.parse("31-12-2009");
Plz help..
Thanks in advance..
Try this:
public class TimeUtils {
public final static long ONE_SECOND = 1000;
public final static long SECONDS = 60;
public final static long ONE_MINUTE = ONE_SECOND * 60;
public final static long MINUTES = 60;
public final static long ONE_HOUR = ONE_MINUTE * 60;
public final static long HOURS = 24;
public final static long ONE_DAY = ONE_HOUR * 24;
private TimeUtils() {
}
/**
* converts time (in milliseconds) to human-readable format
* "<w> days, <x> hours, <y> minutes and (z) seconds"
*/
public static String millisToLongDHMS(long duration) {
StringBuffer res = new StringBuffer();
long temp = 0;
if (duration >= ONE_SECOND) {
temp = duration / ONE_DAY;
if (temp > 0) {
duration -= temp * ONE_DAY;
res.append(temp).append(" day").append(temp > 1 ? "s" : "")
.append(duration >= ONE_MINUTE ? ", " : "");
}
temp = duration / ONE_HOUR;
if (temp > 0) {
duration -= temp * ONE_HOUR;
res.append(temp).append(" hour").append(temp > 1 ? "s" : "")
.append(duration >= ONE_MINUTE ? ", " : "");
}
temp = duration / ONE_MINUTE;
if (temp > 0) {
duration -= temp * ONE_MINUTE;
res.append(temp).append(" minute").append(temp > 1 ? "s" : "");
}
if (!res.toString().equals("") && duration >= ONE_SECOND) {
res.append(" and ");
}
temp = duration / ONE_SECOND;
if (temp > 0) {
res.append(temp).append(" second").append(temp > 1 ? "s" : "");
}
return res.toString();
} else {
return "0 second";
}
}
public static void main(String args[]) {
System.out.println(millisToLongDHMS(123));
System.out.println(millisToLongDHMS((5 * ONE_SECOND) + 123));
System.out.println(millisToLongDHMS(ONE_DAY + ONE_HOUR));
System.out.println(millisToLongDHMS(ONE_DAY + 2 * ONE_SECOND));
System.out.println(millisToLongDHMS(ONE_DAY + ONE_HOUR + (2 * ONE_MINUTE)));
System.out.println(millisToLongDHMS((4 * ONE_DAY) + (3 * ONE_HOUR)
+ (2 * ONE_MINUTE) + ONE_SECOND));
System.out.println(millisToLongDHMS((5 * ONE_DAY) + (4 * ONE_HOUR)
+ ONE_MINUTE + (23 * ONE_SECOND) + 123));
System.out.println(millisToLongDHMS(42 * ONE_DAY));
/*
output :
0 second
5 seconds
1 day, 1 hour
1 day and 2 seconds
1 day, 1 hour, 2 minutes
4 days, 3 hours, 2 minutes and 1 second
5 days, 4 hours, 1 minute and 23 seconds
42 days
*/
}
}
Take a look at the PrettyTime library.
You can check this Comparision of dates
import java.text.SimpleDateFormat;
import java.util.Date;
public class App {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
public static long ms, s, m, h, d, w;
static {
ms = 1;
s = ms * 1000;
m = s * 60;
h = m * 60;
d = h * 24;
w = d * 7;
}
public App() {
Date now = new Date();
Date old = new Date();
try {
old = sdf.parse("12-11-2013");
} catch (Exception e) {
e.printStackTrace();
}
long diff = now.getTime() - old.getTime();
if (diff < this.d) {
System.out.println("Today");
}
else if (diff > this.d && diff < this.d*2) {
System.out.println("Yesterday");
}
System.out.println("Difference: " + msToHms(diff));
}
public String msToHms(long ms) {
int seconds = (int) (ms / this.s) % 60 ;
int minutes = (int) ((ms / this.m) % 60);
int hours = (int) ((ms / this.h) % 24);
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
public static void main(String[] args) {
new App();
}
}
Output
Yesterday
Difference: 07:11:22
You have to implement your own logic based on the time difference and use the corresponding date format.
Lets assume you are getting a date from a server.
Get the device's time and compare to your date.
For your requirements there will be two cases.
The difference between the two date is less then a day, then return "Today" string.
The difference between the two date is grater then a day then use the Simple Date format to format your date as you want.
For comparing dates please see this entry: datecompare

Categories