package javaapplication4;
import java.text.*;
import java.util.*;
/**
*
* @author Stefan Wendelmann
*/
public class JavaApplication4
{
private static SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws ParseException
{
SimpleDateFormat parser = new SimpleDateFormat("dd.MM.YYYY HH:mm:ss.SSS");
Date before = parser.parse("01.10.1990 07:00:00.000");
Date base = parser.parse("01.10.1990 08:00:00.000");
Date after = parser.parse("01.10.1990 09:00:00.000");
printCompare(base, base, "==");
printCompare(base, before, "==");
printCompare(base, before, "<");
printCompare(base, after, "<");
printCompare(base, after, ">");
printCompare(base, before, ">");
printCompare(base, before, "<=");
printCompare(base, base, "<=");
printCompare(base, after, "<=");
printCompare(base, after, ">=");
printCompare(base, base, ">=");
printCompare(base, before, ">=");
}
private static void printCompare (Date a, Date b, String operator){
System.out.println(sdf.format(b)+"\t"+operator+"\t"+sdf.format(a)+"\t"+compareTime(a, b, operator));
}
protected static boolean compareTime(Date a, Date b, String operator)
{
if (a == null)
{
return false;
}
try
{
//Zeit aus Datum holen
// The Magic happens here i only get the Time out of the Date Object
SimpleDateFormat parser = new SimpleDateFormat("HH:mm:ss.SSS");
a = parser.parse(parser.format(a));
b = parser.parse(parser.format(b));
}
catch (ParseException ex)
{
System.err.println(ex);
}
switch (operator)
{
case "==":
return b.compareTo(a) == 0;
case "<":
return b.compareTo(a) < 0;
case ">":
return b.compareTo(a) > 0;
case "<=":
return b.compareTo(a) <= 0;
case ">=":
return b.compareTo(a) >= 0;
default:
throw new IllegalArgumentException("Operator " + operator + " wird für Feldart Time nicht unterstützt!");
}
}
}
run:
08:00:00.000 == 08:00:00.000 true
07:00:00.000 == 08:00:00.000 false
07:00:00.000 < 08:00:00.000 true
09:00:00.000 < 08:00:00.000 false
09:00:00.000 > 08:00:00.000 true
07:00:00.000 > 08:00:00.000 false
07:00:00.000 <= 08:00:00.000 true
08:00:00.000 <= 08:00:00.000 true
09:00:00.000 <= 08:00:00.000 false
09:00:00.000 >= 08:00:00.000 true
08:00:00.000 >= 08:00:00.000 true
07:00:00.000 >= 08:00:00.000 false
BUILD SUCCESSFUL (total time: 0 seconds)