");
}
private static void printRow(PrintStream out, ZoneData zone, List aliases) {
out.print("");
out.print("");
out.print(zone.getStandardOffsetStr());
out.print(" | ");
out.print("");
out.print(zone.getCanonicalID());
out.print(" | ");
out.print("");
if (aliases.size() > 0) {
for (int j=0; j 0) {
out.print(", ");
}
out.print(((ZoneData) aliases.get(j)).getID());
}
}
out.print(" | ");
out.println("
");
}
private static class ZoneData implements Comparable {
private final String iID;
private final DateTimeZone iZone;
ZoneData(String id, DateTimeZone zone) {
iID = id;
iZone = zone;
}
public String getID() {
return iID;
}
public String getCanonicalID() {
return iZone.getID();
}
public boolean isCanonical() {
return getID().equals(getCanonicalID());
}
public String getStandardOffsetStr() {
long millis = cNow;
while (iZone.getOffset(millis) != iZone.getStandardOffset(millis)) {
long next = iZone.nextTransition(millis);
if (next == millis) {
break;
}
millis = next;
}
return cOffsetFormatter.withZone(iZone).print(millis);
}
public int compareTo(Object obj) {
ZoneData other = (ZoneData) obj;
int offsetA = iZone.getStandardOffset(cNow);
int offsetB = other.iZone.getStandardOffset(cNow);
if (offsetA < offsetB) {
return -1;
}
if (offsetA > offsetB) {
return 1;
}
int result = getCanonicalID().compareTo(other.getCanonicalID());
if (result != 0) {
return result;
}
if (isCanonical()) {
if (!other.isCanonical()) {
return -1;
}
} else if (other.isCanonical()) {
return 1;
}
return getID().compareTo(other.getID());
}
}
}
joda-time-2.3/src/example/org/joda/example/time/Examples.java 0000644 0001750 0001750 00000015676 11564251353 023543 0 ustar ebourg ebourg /*
* Copyright 2001-2005 Stephen Colebourne
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.joda.example.time;
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.Instant;
/**
* Example code demonstrating how to use Joda-Time.
*
* @author Stephen Colebourne
*/
public class Examples {
public static void main(String[] args) throws Exception {
try {
new Examples().run();
} catch (Throwable ex) {
ex.printStackTrace();
}
}
private void run() {
runInstant();
System.out.println();
runDateTime();
System.out.println();
}
private void runInstant() {
System.out.println("Instant");
System.out.println("=======");
System.out.println("Instant stores a point in the datetime continuum as millisecs from 1970-01-01T00:00:00Z");
System.out.println("Instant is immutable and thread-safe");
System.out.println(" in = new Instant()");
Instant in = new Instant();
System.out.println("Millisecond time: in.getMillis(): " + in.getMillis());
System.out.println("ISO string version: in.toString(): " + in.toString());
System.out.println("ISO chronology: in.getChronology(): " + in.getChronology());
System.out.println("UTC time zone: in.getDateTimeZone(): " + in.getZone());
System.out.println("Change millis: in.withMillis(0): " + in.withMillis(0L));
System.out.println("");
System.out.println("Convert to Instant: in.toInstant(): " + in.toInstant());
System.out.println("Convert to DateTime: in.toDateTime(): " + in.toDateTime());
System.out.println("Convert to MutableDT: in.toMutableDateTime(): " + in.toMutableDateTime());
System.out.println("Convert to Date: in.toDate(): " + in.toDate());
System.out.println("");
System.out.println(" in2 = new Instant(in.getMillis() + 10)");
Instant in2 = new Instant(in.getMillis() + 10);
System.out.println("Equals ms and chrono: in.equals(in2): " + in.equals(in2));
System.out.println("Compare millisecond: in.compareTo(in2): " + in.compareTo(in2));
System.out.println("Compare millisecond: in.isEqual(in2): " + in.isEqual(in2));
System.out.println("Compare millisecond: in.isAfter(in2): " + in.isAfter(in2));
System.out.println("Compare millisecond: in.isBefore(in2): " + in.isBefore(in2));
}
private void runDateTime() {
System.out.println("DateTime");
System.out.println("=======");
System.out.println("DateTime stores a the date and time using millisecs from 1970-01-01T00:00:00Z internally");
System.out.println("DateTime is immutable and thread-safe");
System.out.println(" in = new DateTime()");
DateTime in = new DateTime();
System.out.println("Millisecond time: in.getMillis(): " + in.getMillis());
System.out.println("ISO string version: in.toString(): " + in.toString());
System.out.println("ISO chronology: in.getChronology(): " + in.getChronology());
System.out.println("Your time zone: in.getDateTimeZone(): " + in.getZone());
System.out.println("Change millis: in.withMillis(0): " + in.withMillis(0L));
System.out.println("");
System.out.println("Get year: in.getYear(): " + in.getYear());
System.out.println("Get monthOfYear: in.getMonthOfYear(): " + in.getMonthOfYear());
System.out.println("Get dayOfMonth: in.getDayOfMonth(): " + in.getDayOfMonth());
System.out.println("...");
System.out.println("Property access: in.dayOfWeek().get(): " + in.dayOfWeek().get());
System.out.println("Day of week as text: in.dayOfWeek().getAsText(): " + in.dayOfWeek().getAsText());
System.out.println("Day as short text: in.dayOfWeek().getAsShortText(): " + in.dayOfWeek().getAsShortText());
System.out.println("Day in french: in.dayOfWeek().getAsText(Locale.FRENCH):" + in.dayOfWeek().getAsText(Locale.FRENCH));
System.out.println("Max allowed value: in.dayOfWeek().getMaximumValue(): " + in.dayOfWeek().getMaximumValue());
System.out.println("Min allowed value: in.dayOfWeek().getMinimumValue(): " + in.dayOfWeek().getMinimumValue());
System.out.println("Copy & set to Jan: in.monthOfYear().setCopy(1): " + in.monthOfYear().setCopy(1));
System.out.println("Copy & add 14 months: in.monthOfYear().addCopy(14): " + in.monthOfYear().addToCopy(14));
System.out.println("Add 14 mnths in field:in.monthOfYear().addWrapFieldCopy(14): " + in.monthOfYear().addWrapFieldToCopy(14));
System.out.println("...");
System.out.println("Convert to Instant: in.toInstant(): " + in.toInstant());
System.out.println("Convert to DateTime: in.toDateTime(): " + in.toDateTime());
System.out.println("Convert to MutableDT: in.toMutableDateTime(): " + in.toMutableDateTime());
System.out.println("Convert to Date: in.toDate(): " + in.toDate());
System.out.println("Convert to Calendar: in.toCalendar(Locale.UK): " + in.toCalendar(Locale.UK).toString().substring(0, 46));
System.out.println("Convert to GregCal: in.toGregorianCalendar(): " + in.toGregorianCalendar().toString().substring(0, 46));
System.out.println("");
System.out.println(" in2 = new DateTime(in.getMillis() + 10)");
DateTime in2 = new DateTime(in.getMillis() + 10);
System.out.println("Equals ms and chrono: in.equals(in2): " + in.equals(in2));
System.out.println("Compare millisecond: in.compareTo(in2): " + in.compareTo(in2));
System.out.println("Compare millisecond: in.isEqual(in2): " + in.isEqual(in2));
System.out.println("Compare millisecond: in.isAfter(in2): " + in.isAfter(in2));
System.out.println("Compare millisecond: in.isBefore(in2): " + in.isBefore(in2));
}
}
joda-time-2.3/src/example/org/joda/example/time/DateTimePerformance.java 0000644 0001750 0001750 00000073421 11564251363 025634 0 ustar ebourg ebourg /*
* Copyright 2001-2005 Stephen Colebourne
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.joda.example.time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.joda.time.DateTime;
import org.joda.time.MutableDateTime;
import org.joda.time.chrono.GJChronology;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
/**
* DateTimePerformance provides various comparisons between the Java supplied
* Date classes and the Joda ones.
*
* @author Stephen Colebourne
*/
public class DateTimePerformance {
private static class Result {
String object = null;
String name = null;
long time = 0;
long avg = 0;
int runs = 0;
}
private static int AVERAGE = 3;
private static int COUNT_VERY_FAST = 5000000;
private static int COUNT_FAST = 200000;
private static int COUNT_SLOW = 20000;
private Map results = new HashMap();
private List resultList = new ArrayList();
private Result result = null;
private long start = 0;
private long end = 0;
/**
* Constructor
*/
public static void main(String[] args) {
try {
new DateTimePerformance();
} catch (Throwable th) {
th.printStackTrace();
}
}
/**
* Constructor
*/
public DateTimePerformance() throws Exception {
checkJodaConstructor1();
checkJISOConstructor1();
checkGCalConstructor1();
checkDateConstructor1();
checkJodaConstructor2();
checkJISOConstructor2();
checkGCalConstructor2();
checkDateConstructor2();
checkJodaConstructor3();
checkJISOConstructor3();
checkGCalConstructor3();
checkDateConstructor3();
checkJodaGetYear();
checkJISOGetYear();
checkGCalGetYear();
checkDateGetYear();
// checkJodaGetMonth();
// checkJISOGetMonth();
// checkGCalGetMonth();
// checkDateGetMonth();
// checkJodaGetDay();
// checkJISOGetDay();
// checkGCalGetDay();
// checkDateGetDay();
checkJodaGetHour();
checkJISOGetHour();
checkGCalGetHour();
checkDateGetHour();
checkJodaSetYear();
checkJISOSetYear();
checkGCalSetYear();
checkDateSetYear();
checkJodaSetGetYear();
checkJISOSetGetYear();
checkGCalSetGetYear();
checkDateSetGetYear();
checkJodaSetHour();
checkJISOSetHour();
checkGCalSetHour();
checkDateSetHour();
checkJodaSetGetHour();
checkJISOSetGetHour();
checkGCalSetGetHour();
checkDateSetGetHour();
checkJodaToString();
checkJISOToString();
checkGCalToString();
checkDateToString();
System.out.println("");
long jodaTotal = 0;
long jisoTotal = 0;
long gcalTotal = 0;
long dateTotal = 0;
for (Iterator it = resultList.iterator(); it.hasNext();) {
Result res = (Result) it.next();
System.out.println(res.object + "." + res.name + ": " + res.avg + "ns");
if (res.object.equals("Joda")) {
jodaTotal += res.avg;
} else if (res.object.equals("JISO")) {
jisoTotal += res.avg;
} else if (res.object.equals("GCal")) {
gcalTotal += res.avg;
} else if (res.object.equals("Date")) {
dateTotal += res.avg;
System.out.println("");
}
}
System.out.println("Joda: " + jodaTotal);
System.out.println("JISO: " + jisoTotal);
System.out.println("GCal: " + gcalTotal);
System.out.println("Date: " + dateTotal);
}
// Constructor using currentTimeMillis()
//------------------------------------------------------------------------
private void checkJodaConstructor1() {
int COUNT = COUNT_SLOW;
DateTime dt = new DateTime(GJChronology.getInstance());
int count = 0;
for (int i = 0; i < AVERAGE; i++) {
start("Joda", "new()");
for (int j = 0; j < COUNT; j++) {
dt = new DateTime(GJChronology.getInstance());
if (count++ < 0) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkJISOConstructor1() {
int COUNT = COUNT_SLOW;
DateTime dt = new DateTime();
int count = 0;
for (int i = 0; i < AVERAGE; i++) {
start("JISO", "new()");
for (int j = 0; j < COUNT; j++) {
dt = new DateTime();
if (count++ < 0) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkGCalConstructor1() {
int COUNT = COUNT_SLOW;
GregorianCalendar dt = new GregorianCalendar();
int count = 0;
for (int i = 0; i < AVERAGE; i++) {
start("GCal", "new()");
for (int j = 0; j < COUNT; j++) {
dt = new GregorianCalendar();
if (count++ < 0) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkDateConstructor1() {
int COUNT = COUNT_SLOW;
Date dt = new Date();
int count = 0;
for (int i = 0; i < AVERAGE; i++) {
start("Date", "new()");
for (int j = 0; j < COUNT; j++) {
dt = new Date();
if (count++ < 0) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
// Constructor using long millis
//------------------------------------------------------------------------
private void checkJodaConstructor2() {
int COUNT = COUNT_VERY_FAST;
DateTime dt = new DateTime(12345L, GJChronology.getInstance());
for (int i = 0; i < AVERAGE; i++) {
start("Joda", "new(millis)");
for (int j = 0; j < COUNT; j++) {
dt = new DateTime(12345L, GJChronology.getInstance());
if (dt == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkJISOConstructor2() {
int COUNT = COUNT_VERY_FAST;
DateTime dt = new DateTime(12345L);
for (int i = 0; i < AVERAGE; i++) {
start("JISO", "new(millis)");
for (int j = 0; j < COUNT; j++) {
dt = new DateTime(12345L);
if (dt == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkGCalConstructor2() {
int COUNT = COUNT_SLOW;
GregorianCalendar dt = new GregorianCalendar();
for (int i = 0; i < AVERAGE; i++) {
start("GCal", "new(millis)");
for (int j = 0; j < COUNT; j++) {
dt = new GregorianCalendar();
dt.setTime(new Date(12345L));
if (dt == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkDateConstructor2() {
int COUNT = COUNT_VERY_FAST;
Date dt = new Date();
for (int i = 0; i < AVERAGE; i++) {
start("Date", "new(millis)");
for (int j = 0; j < COUNT; j++) {
dt = new Date(12345L);
if (dt == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
// Constructor using year month and day
//------------------------------------------------------------------------
private void checkJodaConstructor3() {
int COUNT = COUNT_SLOW;
DateTime dt = new DateTime(1972, 10, 1, 0, 0, 0, 0,
GJChronology.getInstance());
for (int i = 0; i < AVERAGE; i++) {
start("Joda", "new(YMD)");
for (int j = 0; j < COUNT; j++) {
dt = new DateTime(1972, 10, 1, 0, 0, 0, 0,
GJChronology.getInstance());
if (dt == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkJISOConstructor3() {
int COUNT = COUNT_SLOW;
DateTime dt = new DateTime(1972, 10, 1, 0, 0, 0, 0);
for (int i = 0; i < AVERAGE; i++) {
start("JISO", "new(YMD)");
for (int j = 0; j < COUNT; j++) {
dt = new DateTime(1972, 10, 1, 0, 0, 0, 0);
if (dt == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkGCalConstructor3() {
int COUNT = COUNT_SLOW;
GregorianCalendar dt = new GregorianCalendar(1972, 10, 1);
for (int i = 0; i < AVERAGE; i++) {
start("GCal", "new(YMD)");
for (int j = 0; j < COUNT; j++) {
dt = new GregorianCalendar(1972, 10, 1);
if (dt == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkDateConstructor3() {
int COUNT = COUNT_SLOW;
Date dt = new Date();
for (int i = 0; i < AVERAGE; i++) {
start("Date", "new(YMD)");
for (int j = 0; j < COUNT; j++) {
dt = new Date(1972, 10, 1);
if (dt == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
// Get year
//------------------------------------------------------------------------
private void checkJodaGetYear() {
int COUNT = COUNT_VERY_FAST;
DateTime dt = new DateTime(GJChronology.getInstance());
for (int i = 0; i < AVERAGE; i++) {
start("Joda", "getYear");
for (int j = 0; j < COUNT; j++) {
int val = dt.getYear();
if (val == 0) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkJISOGetYear() {
int COUNT = COUNT_VERY_FAST;
DateTime dt = new DateTime();
for (int i = 0; i < AVERAGE; i++) {
start("JISO", "getYear");
for (int j = 0; j < COUNT; j++) {
int val = dt.getYear();
if (val == 0) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkGCalGetYear() {
int COUNT = COUNT_VERY_FAST;
GregorianCalendar dt = new GregorianCalendar();
for (int i = 0; i < AVERAGE; i++) {
start("GCal", "getYear");
for (int j = 0; j < COUNT; j++) {
int val = dt.get(GregorianCalendar.YEAR);
if (val == 0) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkDateGetYear() {
int COUNT = COUNT_FAST;
Date dt = new Date();
for (int i = 0; i < AVERAGE; i++) {
start("Date", "getYear");
for (int j = 0; j < COUNT; j++) {
int val = dt.getYear();
if (val == 0) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
// Get month
//------------------------------------------------------------------------
private void checkJodaGetMonth() {
int COUNT = COUNT_VERY_FAST;
DateTime dt = new DateTime(GJChronology.getInstance());
for (int i = 0; i < AVERAGE; i++) {
start("Joda", "getMonth");
for (int j = 0; j < COUNT; j++) {
int val = dt.getMonthOfYear();
if (val == 0) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkJISOGetMonth() {
int COUNT = COUNT_VERY_FAST;
DateTime dt = new DateTime();
for (int i = 0; i < AVERAGE; i++) {
start("JISO", "getMonth");
for (int j = 0; j < COUNT; j++) {
int val = dt.getMonthOfYear();
if (val == 0) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkGCalGetMonth() {
int COUNT = COUNT_VERY_FAST;
GregorianCalendar dt = new GregorianCalendar();
for (int i = 0; i < AVERAGE; i++) {
start("GCal", "getMonth");
for (int j = 0; j < COUNT; j++) {
int val = dt.get(GregorianCalendar.MONTH);
if (val == 0) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkDateGetMonth() {
int COUNT = COUNT_FAST;
Date dt = new Date();
for (int i = 0; i < AVERAGE; i++) {
start("Date", "getMonth");
for (int j = 0; j < COUNT; j++) {
int val = dt.getMonth();
if (val == 0) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
// Get day
//------------------------------------------------------------------------
private void checkJodaGetDay() {
int COUNT = COUNT_VERY_FAST;
DateTime dt = new DateTime(GJChronology.getInstance());
for (int i = 0; i < AVERAGE; i++) {
start("Joda", "getDay");
for (int j = 0; j < COUNT; j++) {
int val = dt.getDayOfMonth();
if (val == 0) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkJISOGetDay() {
int COUNT = COUNT_VERY_FAST;
DateTime dt = new DateTime();
for (int i = 0; i < AVERAGE; i++) {
start("JISO", "getDay");
for (int j = 0; j < COUNT; j++) {
int val = dt.getDayOfMonth();
if (val == 0) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkGCalGetDay() {
int COUNT = COUNT_VERY_FAST;
GregorianCalendar dt = new GregorianCalendar();
for (int i = 0; i < AVERAGE; i++) {
start("GCal", "getDay");
for (int j = 0; j < COUNT; j++) {
int val = dt.get(GregorianCalendar.DAY_OF_MONTH);
if (val == 0) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkDateGetDay() {
int COUNT = COUNT_FAST;
Date dt = new Date();
for (int i = 0; i < AVERAGE; i++) {
start("Date", "getDay");
for (int j = 0; j < COUNT; j++) {
int val = dt.getDate();
if (val == 0) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
// Get hour
//------------------------------------------------------------------------
private void checkJodaGetHour() {
int COUNT = COUNT_VERY_FAST;
DateTime dt = new DateTime(GJChronology.getInstance());
for (int i = 0; i < AVERAGE; i++) {
start("Joda", "getHour");
for (int j = 0; j < COUNT; j++) {
int val = dt.getHourOfDay();
if (val == -1) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkJISOGetHour() {
int COUNT = COUNT_VERY_FAST;
DateTime dt = new DateTime();
for (int i = 0; i < AVERAGE; i++) {
start("JISO", "getHour");
for (int j = 0; j < COUNT; j++) {
int val = dt.getHourOfDay();
if (val == -1) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkGCalGetHour() {
int COUNT = COUNT_VERY_FAST;
GregorianCalendar dt = new GregorianCalendar();
for (int i = 0; i < AVERAGE; i++) {
start("GCal", "getHour");
for (int j = 0; j < COUNT; j++) {
int val = dt.get(GregorianCalendar.HOUR_OF_DAY);
if (val == -1) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkDateGetHour() {
int COUNT = COUNT_FAST;
Date dt = new Date();
for (int i = 0; i < AVERAGE; i++) {
start("Date", "getHour");
for (int j = 0; j < COUNT; j++) {
int val = dt.getHours();
if (val == -1) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
// Set year
//------------------------------------------------------------------------
private void checkJodaSetYear() {
int COUNT = COUNT_FAST;
// Is it fair to use only MutableDateTime here? You decide.
MutableDateTime dt = new MutableDateTime(GJChronology.getInstance());
for (int i = 0; i < AVERAGE; i++) {
start("Joda", "setYear");
for (int j = 0; j < COUNT; j++) {
dt.setYear(1972);
if (dt == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkJISOSetYear() {
int COUNT = COUNT_FAST;
// Is it fair to use only MutableDateTime here? You decide.
MutableDateTime dt = new MutableDateTime();
for (int i = 0; i < AVERAGE; i++) {
start("JISO", "setYear");
for (int j = 0; j < COUNT; j++) {
dt.setYear(1972);
if (dt == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkGCalSetYear() {
int COUNT = COUNT_VERY_FAST;
GregorianCalendar dt = new GregorianCalendar();
for (int i = 0; i < AVERAGE; i++) {
start("GCal", "setYear");
for (int j = 0; j < COUNT; j++) {
dt.set(GregorianCalendar.YEAR, 1972);
if (dt == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkDateSetYear() {
int COUNT = COUNT_FAST;
Date dt = new Date();
for (int i = 0; i < AVERAGE; i++) {
start("Date", "setYear");
for (int j = 0; j < COUNT; j++) {
dt.setYear(1972);
if (dt == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
// Set then get year
//------------------------------------------------------------------------
private void checkJodaSetGetYear() {
int COUNT = COUNT_FAST;
// Is it fair to use only MutableDateTime here? You decide.
// MutableDateTime dt = new MutableDateTime(GJChronology.getInstance());
// for (int i = 0; i < AVERAGE; i++) {
// start("Joda", "setGetYear");
// for (int j = 0; j < COUNT; j++) {
// dt.setYear(1972);
// int val = dt.getYear();
// if (val < 0) {System.out.println("Anti optimise");}
// }
// end(COUNT);
// }
DateTime dt = new DateTime(GJChronology.getInstance());
for (int i = 0; i < AVERAGE; i++) {
start("Joda", "setGetYear");
for (int j = 0; j < COUNT; j++) {
dt = dt.year().setCopy(1972);
int val = dt.getYear();
if (val < 0) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkJISOSetGetYear() {
int COUNT = COUNT_FAST;
// Is it fair to use only MutableDateTime here? You decide.
// MutableDateTime dt = new MutableDateTime();
// for (int i = 0; i < AVERAGE; i++) {
// start("JISO", "setGetYear");
// for (int j = 0; j < COUNT; j++) {
// dt.setYear(1972);
// int val = dt.getYear();
// if (val < 0) {System.out.println("Anti optimise");}
// }
// end(COUNT);
// }
DateTime dt = new DateTime();
for (int i = 0; i < AVERAGE; i++) {
start("JISO", "setGetYear");
for (int j = 0; j < COUNT; j++) {
dt = dt.year().setCopy(1972);
int val = dt.getYear();
if (val < 0) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkGCalSetGetYear() {
int COUNT = COUNT_FAST;
GregorianCalendar dt = new GregorianCalendar();
for (int i = 0; i < AVERAGE; i++) {
start("GCal", "setGetYear");
for (int j = 0; j < COUNT; j++) {
dt.set(GregorianCalendar.YEAR, 1972);
int val = dt.get(GregorianCalendar.YEAR);
if (val < 0) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkDateSetGetYear() {
int COUNT = COUNT_FAST;
Date dt = new Date();
for (int i = 0; i < AVERAGE; i++) {
start("Date", "setGetYear");
for (int j = 0; j < COUNT; j++) {
dt.setYear(1972);
int val = dt.getYear();
if (val < 0) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
// Set hour
//------------------------------------------------------------------------
private void checkJodaSetHour() {
int COUNT = COUNT_VERY_FAST;
// Is it fair to use only MutableDateTime here? You decide.
MutableDateTime dt = new MutableDateTime(GJChronology.getInstance());
for (int i = 0; i < AVERAGE; i++) {
start("Joda", "setHour");
for (int j = 0; j < COUNT; j++) {
dt.setHourOfDay(13);
if (dt == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkJISOSetHour() {
int COUNT = COUNT_VERY_FAST;
// Is it fair to use only MutableDateTime here? You decide.
MutableDateTime dt = new MutableDateTime();
for (int i = 0; i < AVERAGE; i++) {
start("JISO", "setHour");
for (int j = 0; j < COUNT; j++) {
dt.setHourOfDay(13);
if (dt == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkGCalSetHour() {
int COUNT = COUNT_VERY_FAST;
GregorianCalendar dt = new GregorianCalendar();
for (int i = 0; i < AVERAGE; i++) {
start("GCal", "setHour");
for (int j = 0; j < COUNT; j++) {
dt.set(GregorianCalendar.HOUR_OF_DAY, 13);
if (dt == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkDateSetHour() {
int COUNT = COUNT_FAST;
Date dt = new Date();
for (int i = 0; i < AVERAGE; i++) {
start("Date", "setHour");
for (int j = 0; j < COUNT; j++) {
dt.setHours(13);
if (dt == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
// Set hour
//------------------------------------------------------------------------
private void checkJodaSetGetHour() {
int COUNT = COUNT_VERY_FAST;
// Is it fair to use only MutableDateTime here? You decide.
MutableDateTime dt = new MutableDateTime(GJChronology.getInstance());
for (int i = 0; i < AVERAGE; i++) {
start("Joda", "setGetHour");
for (int j = 0; j < COUNT; j++) {
dt.setHourOfDay(13);
int val = dt.getHourOfDay();
if (dt == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkJISOSetGetHour() {
int COUNT = COUNT_VERY_FAST;
// Is it fair to use only MutableDateTime here? You decide.
MutableDateTime dt = new MutableDateTime();
for (int i = 0; i < AVERAGE; i++) {
start("JISO", "setGetHour");
for (int j = 0; j < COUNT; j++) {
dt.setHourOfDay(13);
int val = dt.getHourOfDay();
if (dt == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkGCalSetGetHour() {
int COUNT = COUNT_VERY_FAST;
GregorianCalendar dt = new GregorianCalendar();
for (int i = 0; i < AVERAGE; i++) {
start("GCal", "setGetHour");
for (int j = 0; j < COUNT; j++) {
dt.set(GregorianCalendar.HOUR_OF_DAY, 13);
int val = dt.get(GregorianCalendar.HOUR_OF_DAY);
if (dt == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkDateSetGetHour() {
int COUNT = COUNT_FAST;
Date dt = new Date();
for (int i = 0; i < AVERAGE; i++) {
start("Date", "setGetHour");
for (int j = 0; j < COUNT; j++) {
dt.setHours(13);
int val = dt.getHours();
if (dt == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
// To formatted string
//------------------------------------------------------------------------
private void checkJodaToString() {
int COUNT = COUNT_SLOW;
DateTime dt = new DateTime(GJChronology.getInstance());
DateTimeFormatter f = DateTimeFormat.forPattern("dd MMM yyyy");
for (int i = 0; i < AVERAGE; i++) {
start("Joda", "toString");
for (int j = 0; j < COUNT; j++) {
String str = dt.toString("dd MMM yyyy");
// String str = dt.toString(f);
if (str == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkJISOToString() {
int COUNT = COUNT_SLOW;
DateTime dt = new DateTime();
DateTimeFormatter f = DateTimeFormat.forPattern("dd MMM yyyy");
for (int i = 0; i < AVERAGE; i++) {
start("JISO", "toString");
for (int j = 0; j < COUNT; j++) {
String str = dt.toString("dd MMM yyyy");
// String str = dt.toString(f);
if (str == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkGCalToString() {
int COUNT = COUNT_SLOW;
GregorianCalendar dt = new GregorianCalendar();
for (int i = 0; i < AVERAGE; i++) {
start("GCal", "toString");
for (int j = 0; j < COUNT; j++) {
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");
String str = sdf.format(dt.getTime());
if (str == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
private void checkDateToString() {
int COUNT = COUNT_SLOW;
Date dt = new Date();
for (int i = 0; i < AVERAGE; i++) {
start("Date", "toString");
for (int j = 0; j < COUNT; j++) {
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");
String str = sdf.format(dt);
if (str == null) {System.out.println("Anti optimise");}
}
end(COUNT);
}
}
//------------------------------------------------------------------------
/**
* Start the stopwatch.
*/
private void start(String str1, String str2) {
result = (Result) results.get(str1 + str2);
if (result == null) {
result = new Result();
result.object = str1;
result.name = str2;
results.put(str1 + str2, result);
resultList.add(result);
}
start = System.currentTimeMillis();
}
/**
* End the stopwatch and print the result.
*/
private void end(int count) {
end = System.currentTimeMillis();
long time = (end - start);
result.time = result.time + time;
result.runs = result.runs + count;
result.avg = (result.time * 1000000) / result.runs;
System.out.print(".");
}
}
joda-time-2.3/src/example/org/joda/example/time/DateTimeFile.dat 0000644 0001750 0001750 00000001264 11564251216 024072 0 ustar ebourg ebourg 1999-12-31T23:59:59
2000-01-01T00:00:00
1969-12-31T23:59:59
1970-01-01T00:00:00
1899-12-31T23:59:59
1900-01-01T00:00:00
# Comment test
1996-02-28T00:00:00
1996-02-29T00:00:00
1996-03-01T00:00:00
1996-12-31T00:00:00
1999-02-28T00:00:00
1999-02-29T00:00:00
1999-03-01T00:00:00
1999-12-31T00:00:00
2000-02-28T00:00:00
2000-02-29T00:00:00
2000-03-01T00:00:00
2000-12-31T00:00:00
# Dates at the Julian-to-Gregorian cutover
1582-10-04T00:00:00
1582-10-05T00:00:00
1582-10-06T00:00:00
1582-10-07T00:00:00
1582-10-08T00:00:00
1582-10-09T00:00:00
1582-10-10T00:00:00
1582-10-11T00:00:00
1582-10-12T00:00:00
1582-10-13T00:00:00
1582-10-14T00:00:00
1582-10-15T00:00:00
joda-time-2.3/src/example/org/joda/example/time/DateTimeBrowser.java 0000644 0001750 0001750 00000120756 11564251353 025021 0 ustar ebourg ebourg /*
* Copyright 2001-2005 Stephen Colebourne
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.joda.example.time;
/*
* Import required Java packages.
*/
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.WindowConstants;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import org.joda.time.DateTime;
/** DateTimeBrowser is a Java Swing application which reads a file contining
* strings and displays DateTime values in a JTable.
* The input strings must be suitable for instantiation
* of DateTime objects. The file is read, and an attempt is made
* to instantiate a DateTimeObject from the input string on each file
* line.
* Comments (beginning with '#') and blank lines may appear in
* the file.
* Error messages may result from invalid input.
* Values calculated from any resulting DateTime objects are placed
* in a JTable and displayed in a JFrame.
*
* @author Guy Allard
* @version 1.0
*/
public class DateTimeBrowser extends JFrame {
//
private String[] mainArgs = null; // Copy of args[] reference.
//
private LoadedFile currFile = null; // New ones possible at
// runtime.
private JScrollPane mainSP = null; // Swapped around at runtime
//
/**
* The getter view menu item.
*/
JMenuItem jmiGetter = null;
/**
* The hexadecimal view menu item.
*/
JMenuItem jmiHex = null;
/**
* The Java Date view menu item.
*/
JMenuItem jmiDate = null;
/**
* The java calendar menu item.
*/
JMenuItem jmiCal = null;
//
// Done deals.
//
private final JFileChooser chooser = new JFileChooser();
private final boolean debugf = false; // debugging flag
private final boolean debugt = true; // debugging flag
/**
* This is the main swing application method. It sets up and displays the
* initial GUI, and controls execution thereafter. Everything else in
* this class is 'private', please read the code.
*/
public static void main(String[] args) {
/*
* Developers Notes:
*
* -No corresponding Junit test class currently
* provided. Test by eyeball of the output.
*
* -Add a menu with Help(About)
* --> TBD.
*
* -Figure out some sane way to set initial default
* column sizes.
*
* -Lots of inner classes here, done in order to keep
* all the .class files easily identifiable. Some of
* this code is pretty ugly, very procedural in nature.
* Lots of very tight coupling between all the classes,
* thinly disguised switch statements, etc ..... This
* code written on the fly, with almost no thought given
* to OO design.
*
* -Also, I'm not really a GUI guy, so forgive any
* transgressions.
*
*/
if ( args.length < 1 ) {
System.err.println("File name is required!");
usage();
System.exit(1);
}
/*
* Instantiate a DateTimeBrowser and invoke it's go method,
* passing the input argument list.
*/
new DateTimeBrowser().go( args );
} // main
/*
* usage A private static method to display usage information to
* the user before an error exit.
*/
private static void usage() {
System.err.println("Usage:");
System.err.print("java ");
System.err.print(DateTimeBrowser.class.getName());
System.err.println(" ");
System.err.println(" contains a list of Strings");
System.err.println("\twhich are valid for DateTime instantiation.");
System.err.println("");
System.err.println("\t-Duse.time.zone=");
System.err.println("\t\tA valid timezone name. If not specified");
System.err.println("\t\tthe OS/user default is used. If sepcified");
System.err.println("\t\tincorrectly, GMT is quietly used.");
System.err.println("\t-Duse.view=");
System.err.println("\t\tAn initial view to be displayed.");
System.err.println("\t\tValid names are: getter, hex, date, cal");
System.err.println("\t\tIf incorrectly specified, getter is used.");
System.err.println("\t\tThis becomes the default view.");
} // usage
/*
* go This method reads the file, creates the table to display,
* the window to display it in, and displays the window.
* @param fileName the name of the file to read.
* @param tryLines An estimate of the number of lines in
* the file.
*/
private void go(String[] args) {
mainArgs = args;
setDefaultTimeZone(); // let user override if needed
// setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
//
JMenuBar menuBar = new JMenuBar();
setJMenuBar( menuBar );
addMenus( menuBar );
/*
* Add a fast close listener
*/
addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
setVisible( false );
dispose();
System.exit(0);
}
}
);
//
// Load current file, prime tables and JFrame.
//
currFile = new LoadedFile( mainArgs[0] );
TableView tView = getDefaultTableView();
resetDefaults( tView );
//
// Set max size at start, and display the window.
//
Dimension screenMax = Toolkit.getDefaultToolkit().getScreenSize();
setSize ( screenMax );
setVisible(true);
}
//
// --> Private implementation methods follow.
//
/*
* getDefaultTableView
*/
private TableView getDefaultTableView() {
// No user input.
String viewStr = System.getProperty("use.view");
if ( viewStr == null ) {
jmiGetter.setEnabled( false );
return new GetterTableView( currFile );
}
// Valid user input.
if ( viewStr.equalsIgnoreCase("hex") ) {
jmiHex.setEnabled( false );
return new HexTableView( currFile );
}
else if ( viewStr.equalsIgnoreCase("date") ) {
jmiDate.setEnabled( false );
return new DateTableView( currFile );
}
else if ( viewStr.equalsIgnoreCase("cal") ) {
jmiCal.setEnabled( false );
return new CalTableView( currFile );
}
else if ( viewStr.equalsIgnoreCase("getter") ) {
jmiGetter.setEnabled( false );
return new GetterTableView( currFile );
}
else { // error by user
System.err.println("View name: " + viewStr + " invalid.");
jmiGetter.setEnabled( false );
return new GetterTableView( currFile );
}
}
/*
* setDefaultTableView
*/
private void setDefaultTableView(String newView) {
System.setProperty( "use.view", newView );
}
/*
* setDefaultTimeZone
*/
private void setDefaultTimeZone() {
String tzName = System.getProperty("use.time.zone");
if ( tzName == null ) return; // Use OS/user default.
//
// If tzName is bogus, not understood by the JRE,
// 'getTimeZone' returns GMT.
//
TimeZone toSet = TimeZone.getTimeZone( tzName );
//
// Set default to whatever was returned.
//
TimeZone.setDefault( toSet );
}
/*
* addMenus
*/
private void addMenus( JMenuBar menuBar) {
//
// Create all the menus.
//
JMenu fileMenu = new JMenu("File");
JMenu viewMenu = new JMenu("View");
//
// Add them to the menubar in order.
//
menuBar.add( fileMenu );
menuBar.add( viewMenu );
//
// Create action objects and menu items.
//
Action open = new OpenAction();
JMenuItem jmiOpen = new JMenuItem( open );
Action exit = new ExitAction();
JMenuItem jmiExit = new JMenuItem( exit );
//
// Next Menu
//
Action getter = new GetterAction();
jmiGetter = new JMenuItem( getter );
getter.setEnabled( true );
//
Action hex = new HexAction();
jmiHex = new JMenuItem( hex );
hex.setEnabled( true );
//
Action date = new DateAction();
jmiDate = new JMenuItem( date );
date.setEnabled( true );
//
Action cal = new CalAction();
jmiCal = new JMenuItem( cal );
cal.setEnabled( true );
//
// Build the file menu.
//
fileMenu.add( jmiOpen );
fileMenu.addSeparator();
fileMenu.add( jmiExit );
//
// Build the view menu.
//
viewMenu.add( jmiGetter );
viewMenu.add( jmiHex );
viewMenu.add( jmiDate );
viewMenu.add( jmiCal );
//
// *temp Developer's code
//
// jmiGetter.setEnabled( false );
//
// JMenuItem getter2 = new JMenuItem( "getter2" );
// getter2.addActionListener( new myMouseListener() );
// viewMenu.add( getter2 );
} // end of addMenus
/*
* A private method to dump the arrays of Object[][]
* if desired by the developer
* @param objs The array of arrays to be dumped.
*/
private void dumpObjs(Object[][] objs, PrintStream out ) {
for (int i = 0; i < objs.length; ++i) {
for (int j = 0; j < objs[i].length; ++j) {
out.println(i + " " + j + " "
+ objs[i][j]);
} // for j
} // for i
}
/*
* enableAll
*/
private void enableAllViews() {
jmiGetter.setEnabled( true );
jmiHex.setEnabled( true );
jmiDate.setEnabled( true );
jmiCal.setEnabled( true );
} // end of enableAllViews
/*
* getADate Returns a new DateTime object reference if possible,
* otherwise null.
* @return retDT A DateTime object reference.
*/
private DateTime getADate(String s) {
DateTime retDT = null;
try
{
retDT = new DateTime( s );
} // the try
catch(IllegalArgumentException pe)
{
// ignore it here, caller sees null
} // the catch
return retDT;
} // getADate
//
private static final String PADCHARS = "00000000000000000000000000000000";
/*
* LPad Return a String, left padded with '0's as specified
* by the caller.
*/
private String LPad(String inStr, int maxLen) {
if (inStr.length() >= maxLen) return inStr.toUpperCase();
String zeroes = PADCHARS.substring(0, maxLen - inStr.length());
String retVal = zeroes + inStr;
return retVal.toUpperCase();
}
/*
* resetDefaults
*/
private void resetDefaults( TableView tView ) {
Object[] colNames = tView.getColNames();
Object[][] tableValues = tView.getCalcdValues();
// dumpObjs( tableValues, System.out);
JTable table = new JTable( tableValues, colNames );
tView.setViewColumnsWidth( table );
setTitle( tView.getViewTitle() );
//
if ( mainSP != null ) getContentPane().remove( mainSP );
mainSP = new JScrollPane( table );
getContentPane().add( mainSP, "Center" );
validate();
} // end of resetDefaults
//
// ----> Private internal classes follow.
//
/*
* LoadedFile This class represents a file that has been loaded
* for viewing.
*/
private class LoadedFile {
// Instance variables
String fileName = null;
ArrayList fileStrings = null;
ArrayList dtObjects = null;
int lineGuess = 0;
/*
* LoadedFile constructor.
*/
LoadedFile(String fileName) {
validateFile( fileName );
this.fileName = fileName;
//
fileStrings = new ArrayList( lineGuess );
dtObjects = new ArrayList( lineGuess );
try
{
BufferedReader rdr =
new BufferedReader( new FileReader( fileName ) );
String inputLine = null;
DateTime calculatedDT = null;
int currLine = 0;
while( (inputLine = rdr.readLine()) != null ) {
currLine++;
inputLine = inputLine.trim();
// Ignore blank and comment lines
if ( inputLine.length() == 0 ) continue;
if ( inputLine.charAt(0) == '#' ) continue;
// Ignore lines which fail DateTime construction
if ( (calculatedDT = getADate(inputLine)) == null ) {
System.err.println("Parse failed for: " + inputLine
+ " at line number " + currLine);
continue;
}
// Add the input file string and DateTime to lists
fileStrings.add( inputLine );
dtObjects.add( calculatedDT );
}
rdr.close();
}
catch(IOException ioe)
{
System.err.println("Load of file: "
+ fileName + " failed!");
ioe.printStackTrace();
System.exit(100);
}
// Try to be efficient (?really?)
fileStrings.trimToSize();
dtObjects.trimToSize();
} // end of LoadedFile() constructor
/*
* General getters.
*/
public String getFileName() { return fileName; }
public int getLineGuess() { return lineGuess; }
public ArrayList getFileStrings() { return fileStrings; }
public ArrayList getDtObjects() { return dtObjects; }
public int getLoadedFileSize() {
if ( dtObjects == null ) return 0;
return dtObjects.size();
}
/*
* validateFile
*/
private void validateFile(String fileName) {
/*
* Verify the user specified file exists and can
* be read.
*/
File f = new File( fileName );
if ( !f.exists() || !f.canRead() ) {
System.err.println("File: " + mainArgs[0]
+ " does not exist or cannot be read!");
usage();
System.exit(2);
}
/*
* Try to get a reasonable estimate of the number of lines
* in the file.
*/
// Java does not do this right IMO. The number of bytes in a
// file is a
// long, but the length of a string is an int. Why?
lineGuess = (int)(f.length() / (long)"YYYY-MM-DDTHH:MM:SS".length());
lineGuess += (lineGuess / 10);
//
// Debugging
//
if ( false ) {
System.out.println("Line guess is: " + lineGuess);
}
} // end of validateFile(String)
} // end of class LoadedFile class
/*
* TableView This abstract class defines the operations
* necessary to create and access the Object arrays
* required to create a JTable.
*/
private abstract class TableView {
protected Object[] colNames = null;
protected Object[][] calcdValues = null;
protected LoadedFile lddFile = null;
//
TableView(LoadedFile lddFile) {
this.lddFile = lddFile;
}
//
public Object[] getColNames() {
return colNames;
}
public Object[][] getCalcdValues() {
return calcdValues;
}
//
abstract Object[] genColNames();
abstract Object[][] genCalcdValues();
abstract String getViewTitle();
abstract void setViewColumnsWidth(JTable jt);
//
} // end of abstract class TableView
/*
* GetterTableView This class implements the operations
* for the GetterView of the Jtable.
*/
private class GetterTableView extends TableView {
//
GetterTableView(LoadedFile lddFile) {
super(lddFile);
setDefaultTableView( "getter" );
colNames = genColNames();
calcdValues = genCalcdValues();
}
/*
* genCalcdValues is required by the base class.
*/
Object[][] genCalcdValues() {
Object[][] retValues = null;
/*
* Create an array of Objects that will contain
* other arrays of Objects. (This is the 'column'
* array).
*/
ArrayList fileStrings = lddFile.getFileStrings();
ArrayList dtObjects = lddFile.getDtObjects();
int numRows = fileStrings.size();
retValues = new Object[numRows][];
int numCols = colNames.length;
// System.err.println("NumCols : " + numCols);
/*
* Prime the array of arrays of Objects, allocating a new
* secondary array for each of the primary array's
* elements.
*/
for (int nextStrNum = 0; nextStrNum < fileStrings.size(); ++ nextStrNum) {
retValues[nextStrNum] = new Object[numCols]; // get the 'col' array
//****
//* This needs to be sync'd with the colNames array.
//****
// Current row, 1st column
int column = 0; // working row value
String fileString = (String)fileStrings.get(nextStrNum);
retValues[nextStrNum][column++] = fileString;
// Current row, 2nd column
DateTime adt = (DateTime)dtObjects.get(nextStrNum);
String adtStr = adt.toString();
retValues[nextStrNum][column++] = adtStr;
// Current row, other columns.
// Order here must match that specified in the colNames
// array.
retValues[nextStrNum][column++] = new Integer( adt.getMillisOfSecond() );
retValues[nextStrNum][column++] = new Integer( adt.getSecondOfMinute() );
retValues[nextStrNum][column++] = new Integer( adt.getMinuteOfHour() );
retValues[nextStrNum][column++] = new Integer( adt.getHourOfDay() );
retValues[nextStrNum][column++] = new Integer( adt.getDayOfWeek() );
retValues[nextStrNum][column++] = new Integer( adt.getDayOfMonth() );
retValues[nextStrNum][column++] = new Integer( adt.getDayOfYear() );
retValues[nextStrNum][column++] = new Integer( adt.getWeekOfWeekyear() );
retValues[nextStrNum][column++] = new Integer( adt.getWeekyear() );
retValues[nextStrNum][column++] = new Integer( adt.getMonthOfYear() );
retValues[nextStrNum][column++] = new Integer( adt.getYear() );
//
} // the for
if ( debugf ) dumpObjs( retValues, System.err );
return retValues;
} // end of genTBValues
/*
* genColNames is required by the base class.
*/
Object[] genColNames() {
Object[] retVal = {
"FileString",
"toString()",
"MillisOfSec",
"SecOfMin",
"MinOfHr",
"HrOfDay",
"DayOfWk",
"DayOfMon",
"DayOfYr",
"WeekOfWY",
"Weekyear",
"MonOfYr",
"Year"
};
return retVal;
}
/*
* getViewTitle
*/
String getViewTitle() {
return "DateTime.getXXX() Method Calculations"
+ " : "
+ TimeZone.getDefault().getDisplayName()
+ " : "
+ " Record Count "
+ currFile.getLoadedFileSize();
}
/*
* setViewColumnLengths
*/
void setViewColumnsWidth(JTable jt) {
/*
* Resize column 0, 1
*/
TableColumnModel colmodel = jt.getColumnModel();
TableColumn col0 = colmodel.getColumn(0);
col0.setPreferredWidth(200);
TableColumn col1 = colmodel.getColumn(1);
col1.setPreferredWidth(200);
return;
}
} // end of class getterTableView
/*
* HexView This class implements the operations for
* the HexView of the file.
*/
private class HexTableView extends TableView {
//
HexTableView(LoadedFile lddFile) {
super(lddFile);
setDefaultTableView( "hex" );
colNames = genColNames();
calcdValues = genCalcdValues();
}
/*
* genCalcdValues is required by the base class.
*/
Object[][] genCalcdValues() {
Object[][] retValues = null;
/*
* Create an array of Objects that will contain
* other arrays of Objects. (This is the 'column'
* array).
*/
ArrayList fileStrings = lddFile.getFileStrings();
ArrayList dtObjects = lddFile.getDtObjects();
int numRows = fileStrings.size();
retValues = new Object[numRows][];
int numCols = colNames.length;
// System.err.println("NumCols : " + numCols);
String fs = "yyyy-MM-dd'T'HH:mm:ss";
DateFormat df = new SimpleDateFormat( fs );
/*
* Prime the array of arrays of Objects, allocating a new
* secondary array for each of the primary array's
* elements.
*/
for (int nextStrNum = 0; nextStrNum < fileStrings.size(); ++ nextStrNum) {
retValues[nextStrNum] = new Object[numCols]; // get the 'col' array
//****
//* This needs to be sync'd with the colNames array.
//****
// Current row, 1st column
int column = 0;
String fileString = (String)fileStrings.get(nextStrNum);
retValues[nextStrNum][column++] = fileString;
// Current row, 2nd column
DateTime adt = (DateTime)dtObjects.get(nextStrNum);
String adtStr = adt.toString();
retValues[nextStrNum][column++] = adtStr;
// Current row, other columns.
// Order here must match that specified in the colNames
// array.
long lVal = adt.getMillis();
Long millis = new Long( lVal );
retValues[nextStrNum][column++] = millis;
String hexVal = Long.toHexString( lVal );
String octalVal = Long.toOctalString( lVal );
retValues[nextStrNum][column++] = "0"+ LPad(octalVal,22);
retValues[nextStrNum][column++] = "0x" + LPad(hexVal,16);
//
Date javaDate = null;
try
{
javaDate = df.parse( fileString );
}
catch(ParseException e)
{
System.err.println("Parse failed for : " + fileString);
// pe.printStackTrace();
}
//
lVal = javaDate.getTime();
millis = new Long( lVal );
hexVal = Long.toHexString( lVal );
octalVal = Long.toOctalString( lVal );
retValues[nextStrNum][column++] = millis;
retValues[nextStrNum][column++] = "0"+ LPad(octalVal,22);
retValues[nextStrNum][column++] = "0x" + LPad(hexVal,16);
//
} // the for
if ( debugf ) dumpObjs( retValues, System.err );
return retValues;
} // end of genTBValues
/*
* genColNames is required by the base class.
*/
Object[] genColNames() {
Object[] retVal = {
"FileString",
"toString()",
"JDT-millis",
"JDT-Oct",
"JDT-Hex",
"Date-millis",
"Date-Oct",
"Date-Hex"
};
return retVal;
}
/*
* getViewTitle
*/
String getViewTitle() {
return "View the long values"
+ " : "
+ TimeZone.getDefault().getDisplayName()
+ " : "
+ " Record Count "
+ currFile.getLoadedFileSize();
}
/*
* setViewColumnLengths
*/
void setViewColumnsWidth(JTable jt) {
return;
}
} // end of class HexTableView
/*
* DateTableView This class implements the operations for
* the java.util.Date of the file.
*/
private class DateTableView extends TableView {
//
DateTableView(LoadedFile lddFile) {
super(lddFile);
setDefaultTableView( "date" );
colNames = genColNames();
calcdValues = genCalcdValues();
}
/*
* genCalcdValues is required by the base class.
*/
Object[][] genCalcdValues() {
Object[][] retValues = null;
/*
* Create an array of Objects that will contain
* other arrays of Objects. (This is the 'column'
* array).
*/
ArrayList fileStrings = lddFile.getFileStrings();
ArrayList dtObjects = lddFile.getDtObjects();
int numRows = fileStrings.size();
retValues = new Object[numRows][];
int numCols = colNames.length;
// System.err.println("NumCols : " + numCols);
/*
* Prime the array of arrays of Objects, allocating a new
* secondary array for each of the primary array's
* elements.
*/
for (int nextStrNum = 0; nextStrNum < fileStrings.size(); ++ nextStrNum) {
retValues[nextStrNum] = new Object[numCols]; // get the 'col' array
//****
//* This needs to be sync'd with the colNames array.
//****
// Current row, 1st column
int column = 0;
String fileString = (String)fileStrings.get(nextStrNum);
retValues[nextStrNum][column++] = fileString;
// Current row, 2nd column
DateTime adt = (DateTime)dtObjects.get(nextStrNum);
String adtStr = adt.toString();
retValues[nextStrNum][column++] = adtStr;
// Current row, other columns.
// Order here must match that specified in the colNames
// array.
long lVal = adt.getMillis();
java.util.Date jDate = new java.util.Date( lVal );
retValues[nextStrNum][column++] = new Integer( jDate.getSeconds() );
retValues[nextStrNum][column++] = new Integer( jDate.getMinutes() );
retValues[nextStrNum][column++] = new Integer( jDate.getHours() );
retValues[nextStrNum][column++] = new Integer( jDate.getDay() );
retValues[nextStrNum][column++] = new Integer( jDate.getDate() );
retValues[nextStrNum][column++] = new Integer( jDate.getMonth() );
retValues[nextStrNum][column++] = new Integer( jDate.getYear() );
//
} // the for
if ( debugf ) dumpObjs( retValues, System.err );
return retValues;
} // end of genTBValues
/*
* genColNames is required by the base class.
*/
Object[] genColNames() {
Object[] retVal = {
"FileString", // 0
"toString()", // 1
"Seconds", // 2
"Minutes", // 3
"Hours", // 4
"Day Of Week", // 5
"Day Of Month", // 6
"Month", // 7
"Year" // 8
};
return retVal;
}
/*
* getViewTitle
*/
String getViewTitle() {
return "java.util.Date getXXX"
+ " : "
+ TimeZone.getDefault().getDisplayName()
+ " : "
+ " Record Count "
+ currFile.getLoadedFileSize();
}
/*
* setViewColumnLengths
*/
void setViewColumnsWidth(JTable jt) {
/*
* Resize column 0, 1
*/
TableColumnModel colmodel = jt.getColumnModel();
TableColumn col0 = colmodel.getColumn(0);
col0.setPreferredWidth(150);
TableColumn col1 = colmodel.getColumn(1);
col1.setPreferredWidth(150);
return;
}
} // end of class DateTableView
/*
* CalTableView This class implements the operations for
* the java.util.Date of the file.
*/
private class CalTableView extends TableView {
//
CalTableView(LoadedFile lddFile) {
super(lddFile);
setDefaultTableView( "cal" );
colNames = genColNames();
calcdValues = genCalcdValues();
}
/*
* genCalcdValues is required by the base class.
*/
Object[][] genCalcdValues() {
Object[][] retValues = null;
/*
* Create an array of Objects that will contain
* other arrays of Objects. (This is the 'column'
* array).
*/
ArrayList fileStrings = lddFile.getFileStrings();
ArrayList dtObjects = lddFile.getDtObjects();
int numRows = fileStrings.size();
retValues = new Object[numRows][];
int numCols = colNames.length;
// System.err.println("NumCols : " + numCols);
/*
* Prime the array of arrays of Objects, allocating a new
* secondary array for each of the primary array's
* elements.
*/
for (int nextStrNum = 0; nextStrNum < fileStrings.size(); ++ nextStrNum) {
retValues[nextStrNum] = new Object[numCols]; // get the 'col' array
//****
//* This needs to be sync'd with the colNames array.
//****
// Current row, 1st column
int column = 0;
String fileString = (String)fileStrings.get(nextStrNum);
retValues[nextStrNum][column++] = fileString;
// Current row, 2nd column
DateTime adt = (DateTime)dtObjects.get(nextStrNum);
String adtStr = adt.toString();
retValues[nextStrNum][column++] = adtStr;
// Current row, other columns.
// Order here must match that specified in the colNames
// array.
long lVal = adt.getMillis();
GregorianCalendar cal = new GregorianCalendar();
cal.setTime( new Date( lVal ) );
cal.setMinimalDaysInFirstWeek(4);
retValues[nextStrNum][column++] = new Integer( cal.get(
Calendar.MILLISECOND ) );
retValues[nextStrNum][column++] = new Integer( cal.get(
Calendar.SECOND ) );
retValues[nextStrNum][column++] = new Integer( cal.get(
Calendar.MINUTE ) );
retValues[nextStrNum][column++] = new Integer( cal.get(
Calendar.HOUR_OF_DAY ) );
retValues[nextStrNum][column++] = new Integer( cal.get(
Calendar.DAY_OF_WEEK ) );
retValues[nextStrNum][column++] = new Integer( cal.get(
Calendar.DAY_OF_MONTH ) );
retValues[nextStrNum][column++] = new Integer( cal.get(
Calendar.DAY_OF_YEAR ) );
retValues[nextStrNum][column++] = new Integer( cal.get(
Calendar.WEEK_OF_YEAR ) );
retValues[nextStrNum][column++] = new Integer( cal.get(
Calendar.MONTH ) );
retValues[nextStrNum][column++] = new Integer( cal.get(
Calendar.YEAR ) );
//
} // the for
if ( debugf ) dumpObjs( retValues, System.err );
return retValues;
} // end of genTBValues
/*
* genColNames is required by the base class.
*/
Object[] genColNames() {
Object[] retVal = {
"FileString", // 0
"toString()", // 1
"Millis", // 2
"Sec", // 3
"Min", // 4
"HrOfDay", // 5
"DayOfWeek", // 6
"DayOfMon", // 7
"DayOfYr", // 8
"WkofYr", // 9
"MonOfYr", // 10
"Year" // 11
};
return retVal;
}
/*
* getViewTitle
*/
String getViewTitle() {
return "java.util.Calendar.get(int)"
+ " : "
+ TimeZone.getDefault().getDisplayName()
+ " : "
+ " Record Count "
+ currFile.getLoadedFileSize();
}
/*
* setViewColumnLengths
*/
void setViewColumnsWidth(JTable jt) {
/*
* Resize column 0, 1
*/
TableColumnModel colmodel = jt.getColumnModel();
TableColumn col0 = colmodel.getColumn(0);
col0.setPreferredWidth(175);
TableColumn col1 = colmodel.getColumn(1);
col1.setPreferredWidth(175);
return;
}
} // end of class CalTableView
/*
* OpenAction
*/
private class OpenAction extends AbstractAction {
/*
* Constructor
*/
public OpenAction() {
super("Open");
} // end of ctor
/*
* actionPerformed
*/
public void actionPerformed(ActionEvent e) {
int result = chooser.showOpenDialog( DateTimeBrowser.this );
String canPath = null;
if ( result == JFileChooser.APPROVE_OPTION ) {
File chosenFile = chooser.getSelectedFile();
try
{
canPath = chosenFile.getCanonicalPath();
}
catch(IOException ioe)
{
System.err.println( "I/O Error on file: "
+ chosenFile );
// Ignore it for now.
}
enableAllViews();
currFile = new LoadedFile( canPath );
TableView tView = getDefaultTableView();
resetDefaults( tView );
} // end of if a file actually chosen.
} // end of actionPerformed
} // end of class OpenAction
/*
* ExitAction
*/
private class ExitAction extends AbstractAction {
/*
* Constructor
*/
public ExitAction() {
super("Exit");
} // end of ctor
/*
* actionPerformed
*/
public void actionPerformed(ActionEvent e) {
DateTimeBrowser.this.setVisible( false );
DateTimeBrowser.this.dispose();
System.exit(0);
} // end of actionPerformed
} // end of class OpenAction
/*
* GetterAction
*/
private class GetterAction extends AbstractAction {
/*
* Constructor
*/
public GetterAction() {
super("Getter");
} // end of ctor
/*
* actionPerformed
*/
public void actionPerformed(ActionEvent e) {
TableView tView = new GetterTableView( currFile );
resetDefaults( tView );
enableAllViews();
jmiGetter.setEnabled( false );
} // end of actionPerformed
} // end of class OpenAction
/*
* HexAction
*/
private class HexAction extends AbstractAction {
/*
* Constructor
*/
public HexAction() {
super("Hex");
} // end of ctor
/*
* actionPerformed
*/
public void actionPerformed(ActionEvent e) {
TableView tView = new HexTableView( currFile );
resetDefaults( tView );
enableAllViews();
jmiHex.setEnabled( false );
} // end of actionPerformed
} // end of class OpenAction
/*
* DateAction
*/
private class DateAction extends AbstractAction {
/*
* Constructor
*/
public DateAction() {
super("Date");
} // end of ctor
/*
* actionPerformed
*/
public void actionPerformed(ActionEvent e) {
TableView tView = new DateTableView( currFile );
resetDefaults( tView );
enableAllViews();
jmiDate.setEnabled( false );
} // end of actionPerformed
} // end of class DateAction
/*
* CalAction
*/
private class CalAction extends AbstractAction {
/*
* Constructor
*/
public CalAction() {
super("Calendar");
} // end of ctor
/*
* actionPerformed
*/
public void actionPerformed(ActionEvent e) {
TableView tView = new CalTableView( currFile );
resetDefaults( tView );
enableAllViews();
jmiCal.setEnabled( false );
} // end of actionPerformed
} // end of class CalAction
} // class DateTimeBrowser
joda-time-2.3/src/example/org/joda/example/time/DateTimeBrowser.README.txt 0000644 0001750 0001750 00000002553 11564251216 025643 0 ustar ebourg ebourg - Joda jar(s) need to be in CLASSPATH. So does the path
which leads to this program's class and inner class files.
- Before running set the default time zone for your
environment (whatever it is will be displayed in the
window title). (See more on TimeZone control below.)
- Once displayed, table columns can resized and rearranged by
drag-n-drop.
- Simple example command lines:
# The default way -
java org.joda.example.DateTimeBrowser DateTimeFile.dat
# Start with the hex view of DateTimes -
java org.joda.example.DateTimeBrowser -Duse.view=hex DateTimeFile.dat
View Control:
The initial view can be controlled from the command line with:
-Duse.view=
Valid values are: getter, hex, date, cal.
Getter is used if not specified or an invalid value is
specified.
TimeZone Control:
The TZ used can be controlled from the command line with:
-Duse.time.zone=xxx
If not specified, the OS/user default is used.
'xxx' should be a valid time zone (e.g. EST). If specified
and 'xxx' is bogus/nonextant, GMT is used.
Regards and Enjoy, Guy Allard
2002-04-18
Last Update: 2002-04-27
joda-time-2.3/src/example/org/joda/example/time/AgeCalculator.java 0000644 0001750 0001750 00000027553 11564251363 024471 0 ustar ebourg ebourg /*
* Copyright 2001-2005 Stephen Colebourne
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.joda.example.time;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import org.joda.time.Chronology;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.DurationField;
import org.joda.time.chrono.ISOChronology;
/**
* AgeCalculator is a small Swing application that computes age from a specific
* birthdate and time zone. Age is broken down into multiple fields, which can
* be independently disabled.
*
* @author Brian S O'Neill
*/
public class AgeCalculator extends JFrame {
static final int
YEARS = 1,
MONTHS = 2,
DAYS = 3,
WEEKYEARS = 4,
WEEKS = 5,
HOURS = 101,
MINUTES = 102,
SECONDS = 103;
public static void main(String[] args) throws Exception {
new AgeCalculator().show();
}
static JComponent fixedSize(JComponent component) {
component.setMaximumSize(component.getPreferredSize());
return component;
}
static JComponent fixedHeight(JComponent component) {
Dimension dim = component.getMaximumSize();
dim.height = component.getPreferredSize().height;
component.setMaximumSize(dim);
return component;
}
Chronology iChronology;
private String iBirthdateStr;
private FieldSet[] iFieldSets;
private Timer iTimer;
public AgeCalculator() {
super();
iChronology = ISOChronology.getInstance();
iBirthdateStr = "1970-01-01T00:00:00";
setTitle("Age Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addMainArea(getContentPane());
addNotify();
Dimension size = getPreferredSize();
setSize(size);
Dimension screenSize = getToolkit().getScreenSize();
setLocation(screenSize.width / 2 - size.width / 2,
screenSize.height / 2 - size.height / 2);
iTimer = new Timer(500, new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateResults();
}
});
iTimer.setInitialDelay(0);
iTimer.start();
}
private void addMainArea(Container container) {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
addTopArea(panel);
panel.add(Box.createVerticalStrut(10));
addBottomArea(panel);
panel.add(Box.createVerticalGlue());
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
container.add(panel);
}
private void addTopArea(Container container) {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(fixedHeight(new JLabel("Birthdate")));
panel.add(Box.createHorizontalStrut(10));
final JTextField birthdateField = new JTextField(iBirthdateStr + ' ');
Document doc = birthdateField.getDocument();
doc.addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
update(e);
}
public void removeUpdate(DocumentEvent e) {
update(e);
}
public void changedUpdate(DocumentEvent e) {
update(e);
}
private void update(DocumentEvent e) {
iBirthdateStr = birthdateField.getText();
updateResults();
}
});
panel.add(fixedHeight(birthdateField));
panel.add(Box.createHorizontalStrut(10));
Object[] ids = DateTimeZone.getAvailableIDs().toArray();
final JComboBox zoneSelector = new JComboBox(ids);
zoneSelector.setSelectedItem(DateTimeZone.getDefault().getID());
panel.add(fixedSize(zoneSelector));
zoneSelector.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String id = (String)zoneSelector.getSelectedItem();
iChronology = ISOChronology.getInstance(DateTimeZone.forID(id));
updateResults();
}
});
container.add(fixedHeight(panel));
}
private void addBottomArea(Container container) {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
ItemListener listener = new ItemListener() {
public void itemStateChanged(ItemEvent e) {
updateResults();
}
};
iFieldSets = new FieldSet[] {
new FieldSet("Month Based", new FieldGroup[] {
new FieldGroup(listener, "Years", YEARS),
new FieldGroup(listener, "Months", MONTHS),
new FieldGroup(listener, "Days", DAYS),
new FieldGroup(listener, "Hours", HOURS),
new FieldGroup(listener, "Minutes", MINUTES),
new FieldGroup(listener, "Seconds", SECONDS)
})
,
new FieldSet("Week Based", new FieldGroup[] {
new FieldGroup(listener, "Weekyears", WEEKYEARS),
new FieldGroup(listener, "Weeks", WEEKS),
new FieldGroup(listener, "Days", DAYS),
new FieldGroup(listener, "Hours", HOURS),
new FieldGroup(listener, "Minutes", MINUTES),
new FieldGroup(listener, "Seconds", SECONDS)
})
};
for (int i=0; i 0) {
panel.add(Box.createHorizontalStrut(10));
}
iFieldSets[i].addTo(panel);
}
panel.add(Box.createVerticalGlue());
container.add(fixedHeight(panel));
}
private void updateResults() {
try {
DateTime dt = new DateTime(iBirthdateStr.trim(), iChronology);
long minuend = System.currentTimeMillis();
long subtrahend = dt.getMillis();
for (int i=0; i