下面列出了java.util.GregorianCalendar#getTimeInMillis ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@NonNull
private Axis xAxis() {
List<AxisValue> axisValues = new ArrayList<AxisValue>();
final java.text.DateFormat timeFormat = hourFormat();
timeFormat.setTimeZone(TimeZone.getDefault());
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(start_time);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
if (calendar.getTimeInMillis()<start_time){
calendar.add(Calendar.HOUR, 1);
}
while (calendar.getTimeInMillis()<end_time){
axisValues.add(new AxisValue((calendar.getTimeInMillis() / FUZZER), (timeFormat.format(calendar.getTimeInMillis())).toCharArray()));
calendar.add(Calendar.HOUR, 1);
}
Axis axis = new Axis();
axis.setValues(axisValues);
axis.setHasLines(true);
return axis;
}
@Test
public void testSqlDate() throws Exception {
Class<LocalDate> clazz = LocalDate.class;
Dao<LocalDate, Object> dao = createDao(clazz, true);
GregorianCalendar c = new GregorianCalendar();
c.set(GregorianCalendar.HOUR_OF_DAY, 0);
c.set(GregorianCalendar.MINUTE, 0);
c.set(GregorianCalendar.SECOND, 0);
c.set(GregorianCalendar.MILLISECOND, 0);
long millis = c.getTimeInMillis();
java.sql.Date val = new java.sql.Date(millis);
String format = "yyyy-MM-dd HH:mm:ss.S";
DateFormat dateFormat = new SimpleDateFormat(format);
String valStr = dateFormat.format(val);
LocalDate foo = new LocalDate();
foo.date = val;
assertEquals(1, dao.create(foo));
Timestamp timestamp = new Timestamp(val.getTime());
testType(dao, foo, clazz, val, timestamp, timestamp, valStr, dataType, DATE_COLUMN, false, true, true, false,
true, false, true, false);
}
private Uri getTimeUntilNextAlarmCondition() {
try {
GregorianCalendar weekRange = new GregorianCalendar();
final long now = weekRange.getTimeInMillis();
setToMidnight(weekRange);
weekRange.roll(Calendar.DATE, 6);
final long nextAlarmMs = (long) XposedHelpers.callMethod(mZenCtrl, "getNextAlarm");
if (nextAlarmMs > 0) {
GregorianCalendar nextAlarm = new GregorianCalendar();
nextAlarm.setTimeInMillis(nextAlarmMs);
setToMidnight(nextAlarm);
if (weekRange.compareTo(nextAlarm) >= 0) {
Object condition = XposedHelpers.callStaticMethod(getZenModeConfigClass(), "toNextAlarmCondition",
mContext, now, nextAlarmMs, SysUiManagers.KeyguardMonitor.getCurrentUserId());
return (Uri) XposedHelpers.getObjectField(condition, "id");
}
}
return null;
} catch (Throwable t) {
XposedBridge.log(t);
return null;
}
}
/**
* Antaa millisekuntiajan ilman vuositietoa. Alusta poistetaan nollat jos niitä on.<br/>
* <b>Poistettu käytöstä, koska testatessa ilmeni ongelmia. Parempi käyttää vain timestampia 'as is'.</b><br/>
* (Katsotaan ehkä joskus myöhemmin, mikäli käytössä olisi mitään järkeä.)
*
* @param millis
* Millisekuntiaika, jota käytetään pohjana sekvenssiarvon generoimiseen
* @return Millisekunnit ilman vuosia
* @deprecated
*/
@Deprecated
protected String getYearlessMillis(long millis) {
GregorianCalendar gregZero = new GregorianCalendar();
gregZero.setTimeInMillis(millis);
gregZero.set(Calendar.MONTH, 0);
gregZero.set(Calendar.DAY_OF_MONTH, 1);
gregZero.set(Calendar.HOUR_OF_DAY, 0);
gregZero.set(Calendar.MINUTE, 0);
gregZero.set(Calendar.SECOND, 0);
gregZero.set(Calendar.MILLISECOND, 0);
long alteredMillis = gregZero.getTimeInMillis();
return Long.toString(millis - alteredMillis).substring(0, 3);
}
static private Axis chartXAxis(int size) {
final Axis xAxis = new Axis();
xAxis.setAutoGenerated(false);
xAxis.setHasTiltedLabels(true);
xAxis.setTiltAngle(-90f);
xAxis.setMaxLabelChars(7);
SimpleDateFormat sdf = new SimpleDateFormat(DateFormat.is24HourFormat(xdrip.getAppContext()) ? "HH:mm" : "a h:mm");
DateFormatSymbols symbols = new DateFormatSymbols(Locale.getDefault());
// OVERRIDE SOME symbols WHILE RETAINING OTHERS
symbols.setAmPmStrings(new String[] { "a", "p" });
sdf.setDateFormatSymbols(symbols);
final java.text.DateFormat timeFormat = sdf;
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
final GregorianCalendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(JoH.tsl());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
xAxis.setAutoGenerated(false);
// TODO make this a better am/pm/24 hour thingy by dividing a day down? DST??? how does that work?? - done on load of value?
List<AxisValue> axisValues = new ArrayList<>();
final int step = size / segments;
final long dayStartMs = calendar.getTimeInMillis();
final long increment = Constants.DAY_IN_MS / segments;
for (int i = 0; i < size; i = i + step) {
calendar.setTimeInMillis(dayStartMs + i*increment);
axisValues.add(new AxisValue(i / step, timeFormat.format(calendar.getTimeInMillis()).toCharArray()));
}
xAxis.setValues(axisValues);
return xAxis;
}
private long getOldestTimestamp(List<PumpHistoryEntry> treatments) {
long dt = Long.MAX_VALUE;
PumpHistoryEntry currentTreatment = null;
for (PumpHistoryEntry treatment : treatments) {
if (treatment.atechDateTime < dt) {
dt = treatment.atechDateTime;
currentTreatment = treatment;
}
}
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: getOldestTimestamp. Oldest entry found: time={}, object={}", dt, currentTreatment);
try {
GregorianCalendar oldestEntryTime = DateTimeUtil.toGregorianCalendar(dt);
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: getOldestTimestamp. oldestEntryTime: {}", DateTimeUtil.toString(oldestEntryTime));
oldestEntryTime.add(Calendar.MINUTE, -2);
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: getOldestTimestamp. oldestEntryTime (-2m): {}, timeInMillis={}", DateTimeUtil.toString(oldestEntryTime), oldestEntryTime.getTimeInMillis());
return oldestEntryTime.getTimeInMillis();
} catch (Exception ex) {
LOG.error("Problem decoding date from last record: {}", currentTreatment);
return 8; // default return of 6 minutes
}
}
public static long convertTime(long time){
GregorianCalendar t1 = new GregorianCalendar(TimeZone.getTimeZone("America/Los_Angeles"));
t1.setTimeInMillis(time);
GregorianCalendar t2 = new GregorianCalendar();
t2.set(t1.get(GregorianCalendar.YEAR), t1.get(GregorianCalendar.MONTH), t1.get(GregorianCalendar.DAY_OF_MONTH), t1.get(GregorianCalendar.HOUR_OF_DAY), t1.get(GregorianCalendar.MINUTE), t1.get(GregorianCalendar.SECOND));
return t2.getTimeInMillis();
}
/**
* Send a message to set the alarm time and date using the system time and date
*
* @return true if the message was sent or false if not
*/
public boolean sendSetTime() {
logger.debug("sendSetTime()");
boolean done = false;
GregorianCalendar cal = new GregorianCalendar();
if (cal.get(Calendar.YEAR) >= 2000) {
logger.debug(String.format("sendSetTime(): sync time %02d/%02d/%04d %02d:%02d:%02d",
cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR),
cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND)));
byte[] dynPart = new byte[6];
dynPart[0] = (byte) cal.get(Calendar.SECOND);
dynPart[1] = (byte) cal.get(Calendar.MINUTE);
dynPart[2] = (byte) cal.get(Calendar.HOUR_OF_DAY);
dynPart[3] = (byte) cal.get(Calendar.DAY_OF_MONTH);
dynPart[4] = (byte) (cal.get(Calendar.MONTH) + 1);
dynPart[5] = (byte) (cal.get(Calendar.YEAR) - 2000);
done = sendMessage(new PowerMaxBaseMessage(PowerMaxSendType.SETTIME, dynPart), false, 0);
cal.set(Calendar.MILLISECOND, 0);
syncTimeCheck = cal.getTimeInMillis();
} else {
logger.warn(
"PowerMax alarm binding: time not synchronized; please correct the date/time of your openHAB server");
syncTimeCheck = null;
}
return done;
}
/**
* Get the expected time in nanosecs at the end of the trace, after
* refreshing.
*
* @return the expected time in nanosecs at the end of the trace
*/
protected long getExpectedEndTimeStamp() {
Date date = new Date((fNbWrittenEvents - 1) * SECOND_TO_MILLISECOND);
// Syslog fills in the year when parsing so we have to do it for the
// expected time stamp as well
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.set(Calendar.YEAR, CURRENT.get(Calendar.YEAR));
if (calendar.after(CURRENT)) {
calendar.set(Calendar.YEAR, CURRENT.get(Calendar.YEAR) - 1);
}
return calendar.getTimeInMillis() * MICROSECOND_TO_NANOSECOND;
}
/**
* Given a calendar and a resolution, gets the origin. It is protected for testing purposes.
* @param calendar
* @param resolution
* @return
*/
protected Date getOrigin(GregorianCalendar calendar, Resolution resolution) {
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second;
switch (resolution) {
case MONTH:
month = 0;
// falls through
case DAY:
day = 1;
// falls through
case HOUR:
hour = 0;
// falls through
case MINUTE:
minute = 0;
// falls through
case SECOND:
second = 0;
break;
default:
// should never be reached
return null;
} // switch
GregorianCalendar gc = new GregorianCalendar(year, month, day, hour, minute, second);
gc.setTimeZone(TimeZone.getTimeZone("UTC"));
return new Date(gc.getTimeInMillis());
}
public static long daysBetween(Calendar start, Calendar end) {
// create copies
GregorianCalendar startDate = new GregorianCalendar(_locale);
GregorianCalendar endDate = new GregorianCalendar(_locale);
// switch calendars to pure Julian mode for correct day-between
// calculation, from the Java API:
// - To obtain a pure Julian calendar, set the change date to
// Date(Long.MAX_VALUE).
startDate.setGregorianChange(new Date(Long.MAX_VALUE));
endDate.setGregorianChange(new Date(Long.MAX_VALUE));
// set them
startDate.setTime(start.getTime());
endDate.setTime(end.getTime());
// force times to be exactly the same
startDate.set(Calendar.HOUR_OF_DAY, 12);
endDate.set(Calendar.HOUR_OF_DAY, 12);
startDate.set(Calendar.MINUTE, 0);
endDate.set(Calendar.MINUTE, 0);
startDate.set(Calendar.SECOND, 0);
endDate.set(Calendar.SECOND, 0);
startDate.set(Calendar.MILLISECOND, 0);
endDate.set(Calendar.MILLISECOND, 0);
// now we should be able to do a "safe" millisecond/day calculation to
// get the number of days, note that we need to include the timezone or daylights savings will get lost!! this is a huge issue
long endMilli = endDate.getTimeInMillis() + endDate.getTimeZone().getOffset(endDate.getTimeInMillis());
long startMilli = startDate.getTimeInMillis() + startDate.getTimeZone().getOffset(startDate.getTimeInMillis());
// calculate # of days, finally
long diff = (endMilli - startMilli) / MILLISECONDS_IN_DAY;
return diff;
}
/**
* Some test code.
*
* @param args ignored.
*/
public static void main(String[] args) {
GregorianCalendar c0 = new GregorianCalendar(2006, 10, 1, 0, 0, 0);
GregorianCalendar c1 = new GregorianCalendar(2006, 10, 1, 11, 37, 43);
c1.set(Calendar.MILLISECOND, 123);
System.out.println("Default: ");
RelativeDateFormat rdf = new RelativeDateFormat(c0.getTimeInMillis());
System.out.println(rdf.format(c1.getTime()));
System.out.println();
System.out.println("Hide milliseconds: ");
rdf.setSecondFormatter(new DecimalFormat("0"));
System.out.println(rdf.format(c1.getTime()));
System.out.println();
System.out.println("Show zero day output: ");
rdf.setShowZeroDays(true);
System.out.println(rdf.format(c1.getTime()));
System.out.println();
System.out.println("Alternative suffixes: ");
rdf.setShowZeroDays(false);
rdf.setDaySuffix(":");
rdf.setHourSuffix(":");
rdf.setMinuteSuffix(":");
rdf.setSecondSuffix("");
System.out.println(rdf.format(c1.getTime()));
System.out.println();
}
public SpecificYearTimestampProvider ( int year )
{
GregorianCalendar cal = new GregorianCalendar ();
cal.set ( Calendar.DAY_OF_YEAR, 1 );
cal.set ( Calendar.HOUR_OF_DAY, 0 );
cal.set ( Calendar.MINUTE, 0 );
cal.set ( Calendar.SECOND, 0 );
cal.set ( Calendar.MILLISECOND, 0 );
cal.set ( Calendar.YEAR, year );
newYear = cal.getTimeInMillis ();
}
public static void main(String[] args) throws Throwable {
int N = 10000;
long t1970 = new java.util.Date(70, 0, 01).getTime();
Random r = new Random();
for (int i = 0; i < N; i++) {
int days = r.nextInt(50) * 365 + r.nextInt(365);
long secs = t1970 + days * 86400 + r.nextInt(86400);
int nanos = r.nextInt(NANOS_PER_SECOND);
int nanos_ms = nanos / 1000000 * 1000000; // millis precision
long millis = secs * 1000 + r.nextInt(1000);
LocalDateTime ldt = LocalDateTime.ofEpochSecond(secs, nanos, ZoneOffset.UTC);
LocalDateTime ldt_ms = LocalDateTime.ofEpochSecond(secs, nanos_ms, ZoneOffset.UTC);
Instant inst = Instant.ofEpochSecond(secs, nanos);
Instant inst_ms = Instant.ofEpochSecond(secs, nanos_ms);
///////////// java.util.Date /////////////////////////
Date jud = new java.util.Date(millis);
Instant inst0 = jud.toInstant();
if (jud.getTime() != inst0.toEpochMilli() ||
!jud.equals(Date.from(inst0))) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: j.u.d -> instant -> j.u.d");
}
// roundtrip only with millis precision
Date jud0 = Date.from(inst_ms);
if (jud0.getTime() != inst_ms.toEpochMilli() ||
!inst_ms.equals(jud0.toInstant())) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: instant -> j.u.d -> instant");
}
//////////// java.util.GregorianCalendar /////////////
GregorianCalendar cal = new GregorianCalendar();
// non-roundtrip of tz name between j.u.tz and j.t.zid
cal.setTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
cal.setGregorianChange(new java.util.Date(Long.MIN_VALUE));
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.setMinimalDaysInFirstWeek(4);
cal.setTimeInMillis(millis);
ZonedDateTime zdt0 = cal.toZonedDateTime();
if (cal.getTimeInMillis() != zdt0.toInstant().toEpochMilli() ||
!cal.equals(GregorianCalendar.from(zdt0))) {
System.out.println("cal:" + cal);
System.out.println("zdt:" + zdt0);
System.out.println("calNew:" + GregorianCalendar.from(zdt0));
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: gcal -> zdt -> gcal");
}
inst0 = cal.toInstant();
if (cal.getTimeInMillis() != inst0.toEpochMilli()) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: gcal -> zdt");
}
ZonedDateTime zdt = ZonedDateTime.of(ldt_ms, ZoneId.systemDefault());
GregorianCalendar cal0 = GregorianCalendar.from(zdt);
if (zdt.toInstant().toEpochMilli() != cal0.getTimeInMillis() ||
!zdt.equals(GregorianCalendar.from(zdt).toZonedDateTime())) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: zdt -> gcal -> zdt");
}
}
///////////// java.util.TimeZone /////////////////////////
for (String zidStr : TimeZone.getAvailableIDs()) {
// TBD: tzdt intergration
if (zidStr.startsWith("SystemV") ||
zidStr.contains("Riyadh8") ||
zidStr.equals("US/Pacific-New") ||
zidStr.equals("EST") ||
zidStr.equals("HST") ||
zidStr.equals("MST")) {
continue;
}
ZoneId zid = ZoneId.of(zidStr, ZoneId.SHORT_IDS);
if (!zid.equals(TimeZone.getTimeZone(zid).toZoneId())) {
throw new RuntimeException("FAILED: zid -> tz -> zid :" + zidStr);
}
TimeZone tz = TimeZone.getTimeZone(zidStr);
// no round-trip for alias and "GMT"
if (!tz.equals(TimeZone.getTimeZone(tz.toZoneId())) &&
!ZoneId.SHORT_IDS.containsKey(zidStr) &&
!zidStr.startsWith("GMT")) {
throw new RuntimeException("FAILED: tz -> zid -> tz :" + zidStr);
}
}
System.out.println("Passed!");
}
public BsonDocument convert(QuantityEventType quantityEventType, Integer gcpLength) {
BsonDocument dbo = new BsonDocument();
dbo.put("eventType", new BsonString("QuantityEvent"));
// Event Time
if (quantityEventType.getEventTime() != null)
dbo.put("eventTime",
new BsonDateTime(quantityEventType.getEventTime().toGregorianCalendar().getTimeInMillis()));
// Event Time zone
if (quantityEventType.getEventTimeZoneOffset() != null)
dbo.put("eventTimeZoneOffset", new BsonString(quantityEventType.getEventTimeZoneOffset()));
// Record Time : according to M5
GregorianCalendar recordTime = new GregorianCalendar();
long recordTimeMilis = recordTime.getTimeInMillis();
dbo.put("recordTime", new BsonDateTime(recordTimeMilis));
// EPC Class
if (quantityEventType.getEpcClass() != null)
dbo.put("epcClass",
new BsonString(MongoWriterUtil.getClassEPC(quantityEventType.getEpcClass(), gcpLength)));
dbo.put("quantity", new BsonInt64(quantityEventType.getQuantity()));
// Business Step
if (quantityEventType.getBizStep() != null)
dbo.put("bizStep", new BsonString(quantityEventType.getBizStep()));
// Disposition
if (quantityEventType.getDisposition() != null)
dbo.put("disposition", new BsonString(quantityEventType.getDisposition()));
// Read Point
if (quantityEventType.getReadPoint() != null) {
ReadPointType readPointType = quantityEventType.getReadPoint();
BsonDocument readPoint = getReadPointObject(readPointType, gcpLength);
dbo.put("readPoint", readPoint);
}
// BizLocation
if (quantityEventType.getBizLocation() != null) {
BusinessLocationType bizLocationType = quantityEventType.getBizLocation();
BsonDocument bizLocation = getBizLocationObject(bizLocationType, gcpLength);
dbo.put("bizLocation", bizLocation);
}
// Vendor Extension
if (quantityEventType.getAny() != null) {
List<Object> objList = quantityEventType.getAny();
BsonDocument map2Save = getAnyMap(objList);
if (map2Save != null && map2Save.isEmpty() == false)
dbo.put("any", map2Save);
}
// BizTransaction
if (quantityEventType.getBizTransactionList() != null) {
BusinessTransactionListType bizListType = quantityEventType.getBizTransactionList();
List<BusinessTransactionType> bizList = bizListType.getBizTransaction();
BsonArray bizTranList = getBizTransactionObjectList(bizList);
dbo.put("bizTransactionList", bizTranList);
}
// Extension
if (quantityEventType.getExtension() != null) {
QuantityEventExtensionType oee = quantityEventType.getExtension();
BsonDocument extension = getQuantityEventExtensionObject(oee);
dbo.put("extension", extension);
}
// Event ID
if (quantityEventType.getBaseExtension() != null) {
if (quantityEventType.getBaseExtension().getEventID() != null) {
dbo.put("eventID", new BsonString(quantityEventType.getBaseExtension().getEventID()));
}
}
// Error Declaration
// If declared, it notes that the event is erroneous
if (quantityEventType.getBaseExtension() != null) {
EPCISEventExtensionType eeet = quantityEventType.getBaseExtension();
ErrorDeclarationType edt = eeet.getErrorDeclaration();
if (edt != null) {
if (edt.getDeclarationTime() != null) {
dbo.put("errorDeclaration", MongoWriterUtil.getErrorDeclaration(edt));
}
}
}
// Build Graph
capture(quantityEventType, gcpLength);
return dbo;
}
public static DataSet<PojoWithCollection> getPojoWithCollection(ExecutionEnvironment env) {
List<PojoWithCollection> data = new ArrayList<>();
List<Pojo1> pojosList1 = new ArrayList<>();
pojosList1.add(new Pojo1("a", "aa"));
pojosList1.add(new Pojo1("b", "bb"));
List<Pojo1> pojosList2 = new ArrayList<>();
pojosList2.add(new Pojo1("a2", "aa2"));
pojosList2.add(new Pojo1("b2", "bb2"));
PojoWithCollection pwc1 = new PojoWithCollection();
pwc1.pojos = pojosList1;
pwc1.key = new IntValue(0);
pwc1.bigInt = BigInteger.valueOf(Long.MAX_VALUE).multiply(BigInteger.TEN);
pwc1.scalaBigInt = BigInt.int2bigInt(10);
pwc1.bigDecimalKeepItNull = null;
// use calendar to make it stable across time zones
GregorianCalendar gcl1 = new GregorianCalendar(2033, 04, 18);
pwc1.sqlDate = new java.sql.Date(gcl1.getTimeInMillis());
pwc1.mixed = new ArrayList<Object>();
Map<StringValue, IntValue> map = new HashMap<>();
map.put(new StringValue("someKey"), new IntValue(1));
pwc1.mixed.add(map);
pwc1.mixed.add(new File("/this/is/wrong"));
pwc1.mixed.add("uhlala");
PojoWithCollection pwc2 = new PojoWithCollection();
pwc2.pojos = pojosList2;
pwc2.key = new IntValue(0);
pwc2.bigInt = BigInteger.valueOf(Long.MAX_VALUE).multiply(BigInteger.TEN);
pwc2.scalaBigInt = BigInt.int2bigInt(31104000);
pwc2.bigDecimalKeepItNull = null;
GregorianCalendar gcl2 = new GregorianCalendar(1976, 4, 3);
pwc2.sqlDate = new java.sql.Date(gcl2.getTimeInMillis()); // 1976
data.add(pwc1);
data.add(pwc2);
return env.fromCollection(data);
}
private static GregorianCalendar parseBigEndianDate(String text,
ParsePosition initialWhere)
{
ParsePosition where = new ParsePosition(initialWhere.getIndex());
int year = parseTimeField(text, where, 4, 0);
if (where.getIndex() != 4 + initialWhere.getIndex())
{
return null;
}
skipOptionals(text, where, "/- ");
int month = parseTimeField(text, where, 2, 1) - 1; // Calendar months are 0...11
skipOptionals(text, where, "/- ");
int day = parseTimeField(text, where, 2, 1);
skipOptionals(text, where, " T");
int hour = parseTimeField(text, where, 2, 0);
skipOptionals(text, where, ": ");
int minute = parseTimeField(text, where, 2, 0);
skipOptionals(text, where, ": ");
int second = parseTimeField(text, where, 2, 0);
char nextC = skipOptionals(text, where, ".");
if (nextC == '.')
{
// fractions of a second: skip upto 19 digits
parseTimeField(text, where, 19, 0);
}
GregorianCalendar dest = newGreg();
try
{
dest.set(year, month, day, hour, minute, second);
// trigger limit tests
dest.getTimeInMillis();
}
catch (IllegalArgumentException ill)
{
return null;
}
initialWhere.setIndex(where.getIndex());
skipOptionals(text, initialWhere, " ");
// dest has at least a year value
return dest;
}
public static void main(String[] args) throws Throwable {
int N = 10000;
long t1970 = new java.util.Date(70, 0, 01).getTime();
Random r = new Random();
for (int i = 0; i < N; i++) {
int days = r.nextInt(50) * 365 + r.nextInt(365);
long secs = t1970 + days * 86400 + r.nextInt(86400);
int nanos = r.nextInt(NANOS_PER_SECOND);
int nanos_ms = nanos / 1000000 * 1000000; // millis precision
long millis = secs * 1000 + r.nextInt(1000);
LocalDateTime ldt = LocalDateTime.ofEpochSecond(secs, nanos, ZoneOffset.UTC);
LocalDateTime ldt_ms = LocalDateTime.ofEpochSecond(secs, nanos_ms, ZoneOffset.UTC);
Instant inst = Instant.ofEpochSecond(secs, nanos);
Instant inst_ms = Instant.ofEpochSecond(secs, nanos_ms);
///////////// java.util.Date /////////////////////////
Date jud = new java.util.Date(millis);
Instant inst0 = jud.toInstant();
if (jud.getTime() != inst0.toEpochMilli() ||
!jud.equals(Date.from(inst0))) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: j.u.d -> instant -> j.u.d");
}
// roundtrip only with millis precision
Date jud0 = Date.from(inst_ms);
if (jud0.getTime() != inst_ms.toEpochMilli() ||
!inst_ms.equals(jud0.toInstant())) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: instant -> j.u.d -> instant");
}
//////////// java.util.GregorianCalendar /////////////
GregorianCalendar cal = new GregorianCalendar();
// non-roundtrip of tz name between j.u.tz and j.t.zid
cal.setTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
cal.setGregorianChange(new java.util.Date(Long.MIN_VALUE));
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.setMinimalDaysInFirstWeek(4);
cal.setTimeInMillis(millis);
ZonedDateTime zdt0 = cal.toZonedDateTime();
if (cal.getTimeInMillis() != zdt0.toInstant().toEpochMilli() ||
!cal.equals(GregorianCalendar.from(zdt0))) {
System.out.println("cal:" + cal);
System.out.println("zdt:" + zdt0);
System.out.println("calNew:" + GregorianCalendar.from(zdt0));
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: gcal -> zdt -> gcal");
}
inst0 = cal.toInstant();
if (cal.getTimeInMillis() != inst0.toEpochMilli()) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: gcal -> zdt");
}
ZonedDateTime zdt = ZonedDateTime.of(ldt_ms, ZoneId.systemDefault());
GregorianCalendar cal0 = GregorianCalendar.from(zdt);
if (zdt.toInstant().toEpochMilli() != cal0.getTimeInMillis() ||
!zdt.equals(GregorianCalendar.from(zdt).toZonedDateTime())) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: zdt -> gcal -> zdt");
}
}
///////////// java.util.TimeZone /////////////////////////
for (String zidStr : TimeZone.getAvailableIDs()) {
// TBD: tzdt intergration
if (zidStr.startsWith("SystemV") ||
zidStr.contains("Riyadh8") ||
zidStr.equals("US/Pacific-New") ||
zidStr.equals("EST") ||
zidStr.equals("HST") ||
zidStr.equals("MST")) {
continue;
}
ZoneId zid = ZoneId.of(zidStr, ZoneId.SHORT_IDS);
if (!zid.equals(TimeZone.getTimeZone(zid).toZoneId())) {
throw new RuntimeException("FAILED: zid -> tz -> zid :" + zidStr);
}
TimeZone tz = TimeZone.getTimeZone(zidStr);
// no round-trip for alias and "GMT"
if (!tz.equals(TimeZone.getTimeZone(tz.toZoneId())) &&
!ZoneId.SHORT_IDS.containsKey(zidStr) &&
!zidStr.startsWith("GMT")) {
throw new RuntimeException("FAILED: tz -> zid -> tz :" + zidStr);
}
}
System.out.println("Passed!");
}
private Timestamp getTimestamp(int year) {
GregorianCalendar cal = new GregorianCalendar(year, 01, 10);
return new Timestamp(cal.getTimeInMillis());
}
public long toLong() {
GregorianCalendar tmp = (GregorianCalendar)clone();
tmp.add(GregorianCalendar.YEAR, 369);
return tmp.getTimeInMillis() + residue;
}