Java Code Examples for java.util.GregorianCalendar#setTimeInMillis()

The following examples show how to use java.util.GregorianCalendar#setTimeInMillis() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BgGraphBuilder.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example 2
Source File: DateTimeTtlValueConverter.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public void convert(String ttl, String startTime) {
    try {
        long start_l, stop_l;
        long ttl_l = Long.parseLong(ttl);
        stop_l = System.currentTimeMillis();
        if (startTime != null)
            stop_l = Long.parseLong(startTime);
        start_l = stop_l - ttl_l;

        GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
        cal.setTimeZone(getTimeZone());
        cal.setTimeInMillis(start_l);
        DatatypeFactory factory = DatatypeFactory.newInstance();
        start = VF.createLiteral(factory.newXMLGregorianCalendar(cal));

        cal.setTimeInMillis(stop_l);
        stop = VF.createLiteral(factory.newXMLGregorianCalendar(cal));
    } catch (DatatypeConfigurationException e) {
        throw new RuntimeException("Exception occurred creating DataTypeFactory", e);
    }
}
 
Example 3
Source File: ResellerShareResultAssembler.java    From development with Apache License 2.0 6 votes vote down vote up
private Period preparePeriod(long periodStartTime, long periodEndTime)
        throws DatatypeConfigurationException {

    Period period = new Period();

    DatatypeFactory df = DatatypeFactory.newInstance();
    GregorianCalendar gc = new GregorianCalendar();

    // start date
    period.setStartDate(BigInteger.valueOf(periodStartTime));
    gc.setTimeInMillis(periodStartTime);
    period.setStartDateIsoFormat(df.newXMLGregorianCalendar(gc).normalize());

    // end date
    period.setEndDate(BigInteger.valueOf(periodEndTime));
    gc.setTimeInMillis(periodEndTime);
    period.setEndDateIsoFormat(df.newXMLGregorianCalendar(gc).normalize());

    return period;
}
 
Example 4
Source File: OidGenerator.java    From KantaCDA-API with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 5
Source File: TestDateTimeUtils.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void test_toCalendar_ZDT() {
    ZonedDateTime zdt = ZonedDateTime.of(2012, 6, 30, 11, 30, 40, 0, PARIS);
    GregorianCalendar calendar = new GregorianCalendar(PARIS_TZ);
    calendar.setFirstDayOfWeek(Calendar.MONDAY);
    calendar.setMinimalDaysInFirstWeek(4);
    calendar.set(2012, 6 - 1, 30, 11, 30, 40);
    calendar.set(Calendar.MILLISECOND, 0);
    calendar.setTimeInMillis(calendar.getTimeInMillis());
    calendar.setGregorianChange(new Date(Long.MIN_VALUE));
    GregorianCalendar test = DateTimeUtils.toGregorianCalendar(zdt);
    assertEquals(test, calendar);
}
 
Example 6
Source File: JUnitOutputReader.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 */
private boolean isValidReportFile(File reportFile) {
    if (!reportFile.canRead()) {
        return false;
    }
    
    long lastModified = reportFile.lastModified();
    long timeDelta = lastModified - timeOfSessionStart;
    
    final Logger logger = Logger.getLogger("org.netbeans.modules.junit.outputreader.timestamps");//NOI18N
    final Level logLevel = FINER;
    if (logger.isLoggable(logLevel)) {
        logger.log(logLevel, "Report file: " + reportFile.getPath());//NOI18N
        
        final GregorianCalendar timeStamp = new GregorianCalendar();
        
        timeStamp.setTimeInMillis(timeOfSessionStart);
        logger.log(logLevel, "Session start:    " + String.format("%1$tT.%2$03d", timeStamp, timeStamp.get(GregorianCalendar.MILLISECOND)));//NOI18N
        
        timeStamp.setTimeInMillis(lastModified);
        logger.log(logLevel, "Report timestamp: " + String.format("%1$tT.%2$03d", timeStamp, timeStamp.get(GregorianCalendar.MILLISECOND)));//NOI18N
    }
    
    if (timeDelta >= 0) {
        return true;
    }
    
    return -timeDelta <= timeOfSessionStart % 1000;
    
}
 
Example 7
Source File: PDTXMLConverter.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Get the passed milliseconds as {@link GregorianCalendar}.
 *
 * @param nMillis
 *        Milliseconds since 1.1.1970
 * @return Never <code>null</code>.
 * @since 9.1.8
 */
@Nonnull
public static GregorianCalendar getCalendarDefaultTimeZone (final long nMillis)
{
  final GregorianCalendar aCalendar = new GregorianCalendar (PDTConfig.getDefaultTimeZone (),
                                                             Locale.getDefault (Locale.Category.FORMAT));
  aCalendar.setTimeInMillis (nMillis);
  return aCalendar;
}
 
Example 8
Source File: SpearalDateTime.java    From spearal-java with Apache License 2.0 5 votes vote down vote up
public static SpearalDateTime forDate(Date date) {
	GregorianCalendar calendar = new GregorianCalendar(UTC, Locale.US);
	calendar.setTimeInMillis(date.getTime());
	return new SpearalDateTime(
		calendar.get(Calendar.YEAR),
		calendar.get(Calendar.MONTH) + 1,
		calendar.get(Calendar.DATE),
		calendar.get(Calendar.HOUR_OF_DAY),
		calendar.get(Calendar.MINUTE),
		calendar.get(Calendar.SECOND),
		calendar.get(Calendar.MILLISECOND) * 1000000,
		true, true
	);
}
 
Example 9
Source File: DateTimeUtils.java    From jingtum-lib-java with MIT License 5 votes vote down vote up
/**
 * 转换sql timestamp到日历函数
 * 
 * @param date
 * @return
 */
public static Calendar convSqlTimestampToUtilCalendar(Timestamp date) {
    if (date == null) {
        return null;
    } else {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTimeInMillis(date.getTime());
        return gc;
    }
}
 
Example 10
Source File: JAXBWriter.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
public XMLGregorianCalendar convertDate(Instant date) {
    if (date == null) {
        return null;
    }

    GregorianCalendar c = new GregorianCalendar();
    c.setTimeInMillis(date.toEpochMilli());
    return datatypeFactory.newXMLGregorianCalendar(c).normalize();
}
 
Example 11
Source File: RelativeTimeFormatterTest.java    From jsmpp with Apache License 2.0 5 votes vote down vote up
@Test(groups = "checkintest")
public void formatRelativeDateMonthFebruary() {
  // for Java 8, the relative time could be calculated better
  GregorianCalendar smscDate = new GregorianCalendar(TimeZone.getTimeZone("Pacific/Midway"));
  smscDate.set(2015, Calendar.FEBRUARY, 1, 0, 11, 22);

  GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("Pacific/Midway"));
  date.setTimeInMillis(smscDate.getTimeInMillis());
  date.add(Calendar.MONTH, 1);
  assertEquals(relativeTimeFormatter.format(date, smscDate), "000028000000000R");
}
 
Example 12
Source File: MongoBackendImpl.java    From fiware-cygnus with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void insertContextDataAggregated(String dbName, String collectionName, long recvTimeTs, String entityId,
        String entityType, String attrName, String attrType, HashMap<String, Integer> counts,
        boolean[] resolutions) throws Exception {
    // Preprocess some values
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
    calendar.setTimeInMillis(recvTimeTs);

    // Insert the data in an aggregated fashion for each resolution type
    if (resolutions[0]) {
        insertContextDataAggregatedForResoultion(dbName, collectionName, calendar, entityId, entityType,
                attrName, attrType, counts, Resolution.SECOND);
    } // if

    if (resolutions[1]) {
        insertContextDataAggregatedForResoultion(dbName, collectionName, calendar, entityId, entityType,
                attrName, attrType, counts, Resolution.MINUTE);
    } // if

    if (resolutions[2]) {
        insertContextDataAggregatedForResoultion(dbName, collectionName, calendar, entityId, entityType,
                attrName, attrType, counts, Resolution.HOUR);
    } // if

    if (resolutions[3]) {
        insertContextDataAggregatedForResoultion(dbName, collectionName, calendar, entityId, entityType,
                attrName, attrType, counts, Resolution.DAY);
    } // if

    if (resolutions[4]) {
        insertContextDataAggregatedForResoultion(dbName, collectionName, calendar, entityId, entityType,
                attrName, attrType, counts, Resolution.MONTH);
    } // if
}
 
Example 13
Source File: JavatimeTest.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
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!");
    }
 
Example 14
Source File: TCalendar.java    From jexer with MIT License 4 votes vote down vote up
/**
 * Draw the combobox down arrow.
 */
@Override
public void draw() {
    CellAttributes backgroundColor = getTheme().getColor(
            "tcalendar.background");
    CellAttributes dayColor = getTheme().getColor(
            "tcalendar.day");
    CellAttributes selectedDayColor = getTheme().getColor(
            "tcalendar.day.selected");
    CellAttributes arrowColor = getTheme().getColor(
            "tcalendar.arrow");
    CellAttributes titleColor = getTheme().getColor(
            "tcalendar.title");

    // Fill in the interior background
    for (int i = 0; i < getHeight(); i++) {
        getScreen().hLineXY(0, i, getWidth(), ' ', backgroundColor);
    }

    // Draw the title
    String title = String.format("%tB %tY", displayCalendar,
        displayCalendar);
    int titleLeft = (getWidth() - title.length() - 2) / 2;
    getScreen().putCharXY(titleLeft, 0, ' ', titleColor);
    getScreen().putStringXY(titleLeft + 1, 0, title, titleColor);
    getScreen().putCharXY(titleLeft + title.length() + 1, 0, ' ',
        titleColor);

    // Arrows
    getScreen().putCharXY(1, 0, GraphicsChars.LEFTARROW, arrowColor);
    getScreen().putCharXY(getWidth() - 2, 0, GraphicsChars.RIGHTARROW,
        arrowColor);

    /*
     * Now draw out the days.
     */
    getScreen().putStringXY(0, 1, "  S   M   T   W   T   F   S ", dayColor);
    int lastDayNumber = displayCalendar.getActualMaximum(
            Calendar.DAY_OF_MONTH);
    GregorianCalendar firstOfMonth = new GregorianCalendar();
    firstOfMonth.setTimeInMillis(displayCalendar.getTimeInMillis());
    firstOfMonth.set(Calendar.DAY_OF_MONTH, 1);
    int dayOf1st = firstOfMonth.get(Calendar.DAY_OF_WEEK) - 1;
    int dayColumn = dayOf1st * 4;
    int row = 2;

    int dayOfMonth = 1;
    while (dayOfMonth <= lastDayNumber) {
        if (dayColumn == 4 * 7) {
            dayColumn = 0;
            row++;
        }
        if ((dayOfMonth == calendar.get(Calendar.DAY_OF_MONTH))
            && (displayCalendar.get(Calendar.MONTH) == calendar.get(
                Calendar.MONTH))
            && (displayCalendar.get(Calendar.YEAR) == calendar.get(
                Calendar.YEAR))
        ) {
            getScreen().putStringXY(dayColumn, row,
                String.format(" %2d ", dayOfMonth), selectedDayColor);
        } else {
            getScreen().putStringXY(dayColumn, row,
                String.format(" %2d ", dayOfMonth), dayColor);
        }
        dayColumn += 4;
        dayOfMonth++;
    }

}
 
Example 15
Source File: MyTargetAdapter.java    From googleads-mobile-android-mediation with Apache License 2.0 4 votes vote down vote up
@Override
public void requestInterstitialAd(Context context,
    MediationInterstitialListener mediationInterstitialListener,
    Bundle serverParameters,
    MediationAdRequest mediationAdRequest,
    Bundle mediationExtras) {
  int slotId = MyTargetTools.checkAndGetSlotId(context, serverParameters);
  Log.d(TAG, "Requesting myTarget interstitial mediation, slotId: " + slotId);

  if (slotId < 0) {
    if (mediationInterstitialListener != null) {
      mediationInterstitialListener.onAdFailedToLoad(
          MyTargetAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST);
    }
    return;
  }

  MyTargetInterstitialListener bannerListener = null;
  if (mediationInterstitialListener != null) {
    bannerListener = new MyTargetInterstitialListener(mediationInterstitialListener);
  }

  if (mInterstitial != null) {
    mInterstitial.destroy();
  }

  mInterstitial = new InterstitialAd(slotId, context);
  CustomParams params = mInterstitial.getCustomParams();
  params.setCustomParam(
      MyTargetTools.PARAM_MEDIATION_KEY, MyTargetTools.PARAM_MEDIATION_VALUE);
  if (mediationAdRequest != null) {
    int gender = mediationAdRequest.getGender();
    Log.d(TAG, "Set gender to " + gender);
    params.setGender(gender);
    Date date = mediationAdRequest.getBirthday();
    if (date != null && date.getTime() != -1) {
      GregorianCalendar calendar = new GregorianCalendar();
      GregorianCalendar calendarNow = new GregorianCalendar();

      calendar.setTimeInMillis(date.getTime());
      int age = calendarNow.get(GregorianCalendar.YEAR)
          - calendar.get(GregorianCalendar.YEAR);
      if (age >= 0) {
        Log.d(TAG, "Set age to " + age);
        params.setAge(age);
      }
    }
  }
  mInterstitial.setListener(bannerListener);
  mInterstitial.load();
}
 
Example 16
Source File: InputDialogContainer.java    From 365browser with Apache License 2.0 4 votes vote down vote up
protected void showPickerDialog(final int dialogType, double dialogValue,
        double min, double max, double step) {
    Calendar cal;
    // |dialogValue|, |min|, |max| mean different things depending on the |dialogType|.
    // For input type=month is the number of months since 1970.
    // For input type=time it is milliseconds since midnight.
    // For other types they are just milliseconds since 1970.
    // If |dialogValue| is NaN it means an empty value. We will show the current time.
    if (Double.isNaN(dialogValue)) {
        cal = Calendar.getInstance();
        cal.set(Calendar.MILLISECOND, 0);
    } else {
        if (dialogType == TextInputType.MONTH) {
            cal = MonthPicker.createDateFromValue(dialogValue);
        } else if (dialogType == TextInputType.WEEK) {
            cal = WeekPicker.createDateFromValue(dialogValue);
        } else {
            GregorianCalendar gregorianCalendar =
                    new GregorianCalendar(TimeZone.getTimeZone("UTC"));
            // According to the HTML spec we only use the Gregorian calendar
            // so we ignore the Julian/Gregorian transition.
            gregorianCalendar.setGregorianChange(new Date(Long.MIN_VALUE));
            gregorianCalendar.setTimeInMillis((long) dialogValue);
            cal =  gregorianCalendar;
        }
    }
    if (dialogType == TextInputType.DATE) {
        showPickerDialog(dialogType,
                cal.get(Calendar.YEAR),
                cal.get(Calendar.MONTH),
                cal.get(Calendar.DAY_OF_MONTH),
                0, 0, 0, 0, 0, min, max, step);
    } else if (dialogType == TextInputType.TIME) {
        showPickerDialog(dialogType, 0, 0, 0,
                cal.get(Calendar.HOUR_OF_DAY),
                cal.get(Calendar.MINUTE),
                0, 0, 0, min, max, step);
    } else if (dialogType == TextInputType.DATE_TIME
            || dialogType == TextInputType.DATE_TIME_LOCAL) {
        showPickerDialog(dialogType,
                cal.get(Calendar.YEAR),
                cal.get(Calendar.MONTH),
                cal.get(Calendar.DAY_OF_MONTH),
                cal.get(Calendar.HOUR_OF_DAY),
                cal.get(Calendar.MINUTE),
                cal.get(Calendar.SECOND),
                cal.get(Calendar.MILLISECOND),
                0, min, max, step);
    } else if (dialogType == TextInputType.MONTH) {
        showPickerDialog(dialogType, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), 0,
                0, 0, 0, 0, 0, min, max, step);
    } else if (dialogType == TextInputType.WEEK) {
        int year = WeekPicker.getISOWeekYearForDate(cal);
        int week = WeekPicker.getWeekForDate(cal);
        showPickerDialog(dialogType, year, 0, 0, 0, 0, 0, 0, week, min, max, step);
    }
}
 
Example 17
Source File: GregorianCalendarRandomizer.java    From easy-random with MIT License 4 votes vote down vote up
@Override
public GregorianCalendar getRandomValue() {
    GregorianCalendar gregorianCalendar = new GregorianCalendar();
    gregorianCalendar.setTimeInMillis(Math.abs(delegate.getRandomValue()));
    return gregorianCalendar;
}
 
Example 18
Source File: DurationImpl.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * <p>Constructs a new Duration object by specifying the duration
 * in milliseconds.</p>
 *
 * @param durationInMilliSeconds
 *      The length of the duration in milliseconds.
 */
protected DurationImpl(final long durationInMilliSeconds) {

    long l = durationInMilliSeconds;

    if (l > 0) {
        signum = 1;
    } else if (l < 0) {
        signum = -1;
        if (l == 0x8000000000000000L) {
            // negating 0x8000000000000000L causes an overflow
            l++;
        }
        l *= -1;
    } else {
        signum = 0;
    }

    // let GregorianCalendar do the heavy lifting
    GregorianCalendar gregorianCalendar = new GregorianCalendar(GMT);

    // duration is the offset from the Epoch
    gregorianCalendar.setTimeInMillis(l);

    // now find out how much each field has changed
    long int2long = 0L;

    // years
    int2long = gregorianCalendar.get(Calendar.YEAR) - 1970;
    this.years = BigInteger.valueOf(int2long);

    // months
    int2long = gregorianCalendar.get(Calendar.MONTH);
    this.months = BigInteger.valueOf(int2long);

    // days
    int2long = gregorianCalendar.get(Calendar.DAY_OF_MONTH) - 1;
    this.days = BigInteger.valueOf(int2long);

    // hours
    int2long = gregorianCalendar.get(Calendar.HOUR_OF_DAY);
    this.hours = BigInteger.valueOf(int2long);

    // minutes
    int2long = gregorianCalendar.get(Calendar.MINUTE);
    this.minutes = BigInteger.valueOf(int2long);

    // seconds & milliseconds
    int2long = (gregorianCalendar.get(Calendar.SECOND) * 1000)
                + gregorianCalendar.get(Calendar.MILLISECOND);
    this.seconds = BigDecimal.valueOf(int2long, 3);
}
 
Example 19
Source File: DurationImpl.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
/**
 * <p>Constructs a new Duration object by specifying the duration
 * in milliseconds.</p>
 *
 * @param durationInMilliSeconds
 *      The length of the duration in milliseconds.
 */
protected DurationImpl(final long durationInMilliSeconds) {

    long l = durationInMilliSeconds;

    if (l > 0) {
        signum = 1;
    } else if (l < 0) {
        signum = -1;
        if (l == 0x8000000000000000L) {
            // negating 0x8000000000000000L causes an overflow
            l++;
        }
        l *= -1;
    } else {
        signum = 0;
    }

    // let GregorianCalendar do the heavy lifting
    GregorianCalendar gregorianCalendar = new GregorianCalendar(GMT);

    // duration is the offset from the Epoch
    gregorianCalendar.setTimeInMillis(l);

    // now find out how much each field has changed
    long int2long = 0L;

    // years
    int2long = gregorianCalendar.get(Calendar.YEAR) - 1970;
    this.years = BigInteger.valueOf(int2long);

    // months
    int2long = gregorianCalendar.get(Calendar.MONTH);
    this.months = BigInteger.valueOf(int2long);

    // days
    int2long = gregorianCalendar.get(Calendar.DAY_OF_MONTH) - 1;
    this.days = BigInteger.valueOf(int2long);

    // hours
    int2long = gregorianCalendar.get(Calendar.HOUR_OF_DAY);
    this.hours = BigInteger.valueOf(int2long);

    // minutes
    int2long = gregorianCalendar.get(Calendar.MINUTE);
    this.minutes = BigInteger.valueOf(int2long);

    // seconds & milliseconds
    int2long = (gregorianCalendar.get(Calendar.SECOND) * 1000)
                + gregorianCalendar.get(Calendar.MILLISECOND);
    this.seconds = BigDecimal.valueOf(int2long, 3);
}
 
Example 20
Source File: JavatimeTest.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
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!");
    }