Java Code Examples for java.util.Calendar#setTimeZone()

The following examples show how to use java.util.Calendar#setTimeZone() . 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: TestThaiBuddhistChronoImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider="RangeVersusCalendar")
public void test_ThaiBuddhistChrono_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
    Locale locale = Locale.forLanguageTag("th-TH--u-ca-buddhist");
    assertEquals(locale.toString(), "th_TH", "Unexpected locale");
    Calendar cal = java.util.Calendar.getInstance(locale);
    assertEquals(cal.getCalendarType(), "buddhist", "Unexpected calendar type");

    ThaiBuddhistDate thaiDate = ThaiBuddhistChronology.INSTANCE.date(isoStartDate);

    cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
    cal.set(Calendar.YEAR, thaiDate.get(ChronoField.YEAR));
    cal.set(Calendar.MONTH, thaiDate.get(ChronoField.MONTH_OF_YEAR) - 1);
    cal.set(Calendar.DAY_OF_MONTH, thaiDate.get(ChronoField.DAY_OF_MONTH));

    while (thaiDate.isBefore(isoEndDate)) {
        assertEquals(thaiDate.get(ChronoField.DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + thaiDate + ";  cal: " + cal);
        assertEquals(thaiDate.get(ChronoField.MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + thaiDate);
        assertEquals(thaiDate.get(ChronoField.YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + thaiDate);

        thaiDate = thaiDate.plus(1, ChronoUnit.DAYS);
        cal.add(Calendar.DAY_OF_MONTH, 1);
    }
}
 
Example 2
Source File: TimezoneOffsetFunctionIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testInsertingRetrivingTimestamp() throws Exception {
    Connection conn = DriverManager.getConnection(getUrl());
	String t = generateUniqueName();
	String ddl = "CREATE TABLE " + t + " (K INTEGER NOT NULL PRIMARY KEY, V TIMESTAMP)";
       conn.createStatement().execute(ddl);
       String dml = "UPSERT INTO " + t + " VALUES (?, ?)";
       PreparedStatement stmt = conn.prepareStatement(dml);
       stmt.setInt(1, 1);
       Calendar cal = Calendar.getInstance();
       cal.setTimeZone(TimeZone.getTimeZone("US/Hawaii"));
       long time = System.currentTimeMillis();
       stmt.setTimestamp(2, new Timestamp(time), cal);
       stmt.executeUpdate();
       conn.commit();
       String query = "SELECT V FROM " + t;
       ResultSet rs = conn.createStatement().executeQuery(query);
       rs.next();
       assertEquals(new Timestamp(time), rs.getTimestamp(1));
       assertEquals(new Timestamp(time), rs.getTimestamp("V"));
       assertEquals(new Timestamp(time), rs.getTimestamp(1, cal));
       assertEquals(new Timestamp(time), rs.getTimestamp("V", cal));
   }
 
Example 3
Source File: DateUtil.java    From PoetryWeather with Apache License 2.0 6 votes vote down vote up
/**
 * 获取今天往后一周的集合
 */
public static List<String> getWeeks() {
    List<String> weeks = new ArrayList<>();
    String mMonth;
    String mDay;
    int current_day;
    int current_month;
    final Calendar c = Calendar.getInstance();
    c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
    current_day = c.get(Calendar.DAY_OF_MONTH);
    current_month = c.get(Calendar.MONTH);
    for (int i = 0; i < 7; i++) {
        c.clear();//记住一定要clear一次
        c.set(Calendar.MONTH, current_month);
        c.set(Calendar.DAY_OF_MONTH, current_day);
        c.add(Calendar.DATE, +i);
        mMonth = String.valueOf(c.get(Calendar.MONTH) + 1);
        mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
        String date = mMonth + "-" + mDay;
        weeks.add(date);
    }
    return weeks;
}
 
Example 4
Source File: Helper.java    From smartcoins-wallet with MIT License 6 votes vote down vote up
public static String convertTimeZoneToRegion(Date date, Context context) {

        if (Helper.containKeySharePref(context, context.getString(R.string.date_time_zone))) {
            String dtz = Helper.fetchStringSharePref(context, context.getString(R.string.date_time_zone));
            TimeZone tz = TimeZone.getTimeZone(dtz);
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeZone(tz);
            String region = calendar.getTimeZone().getID();
            String[] arr = region.split("/");
            for (String ss : arr) {
                if (ss.equals("Europe")) {
                    region = "CET";
                }
            }
            return region;

        } else {
            return "UTC";
        }
    }
 
Example 5
Source File: GeneralizedTimeTest.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
/**
 * Tests constructor with calendar object.
 */
@Test
public void testCalendar() throws ParseException
{
    Calendar calendar = new GregorianCalendar( GMT, Locale.ROOT );
    calendar.set( Calendar.YEAR, 2008 );
    calendar.set( Calendar.MONTH, 0 );
    calendar.set( Calendar.DAY_OF_MONTH, 2 );
    calendar.set( Calendar.HOUR_OF_DAY, 12 );
    calendar.set( Calendar.MINUTE, 13 );
    calendar.set( Calendar.SECOND, 14 );
    calendar.set( Calendar.MILLISECOND, 222 );
    calendar.setTimeZone( TimeZone.getTimeZone( "GMT" ) );

    GeneralizedTime generalizedTime = new GeneralizedTime( calendar );
    String result = generalizedTime.toGeneralizedTime();
    assertEquals( "20080102121314.222Z", result );
}
 
Example 6
Source File: DateUtils.java    From oodt with Apache License 2.0 6 votes vote down vote up
public static synchronized Calendar toCalendar(String calString, FormatType formatType)
        throws ParseException {
    Calendar cal = Calendar.getInstance();
    switch (formatType) {
        case LOCAL_FORMAT:
            cal.setTimeInMillis(localFormat.parse(calString).getTime());
            break;
        case TAI_FORMAT:
            cal.setTimeZone(createTaiTimeZone(Integer.parseInt(calString
                .substring(calString.length() - 2))));
            calString = calString.substring(0, calString.length() - 5);
            cal.setTimeInMillis(taiFormat.parse(calString).getTime());
            break;
        case UTC_FORMAT:
            cal.setTimeZone(TimeZone.getTimeZone("UTC"));
            cal.setTimeInMillis(utcFormat.parse(calString).getTime());
            break;
        default:
            cal.setTimeInMillis(localFormat.parse(calString).getTime());
    }
    return cal;
}
 
Example 7
Source File: TestThaiBuddhistChronoImpl.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider="RangeVersusCalendar")
public void test_ThaiBuddhistChrono_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
    Locale locale = Locale.forLanguageTag("th-TH--u-ca-buddhist");
    assertEquals(locale.toString(), "th_TH", "Unexpected locale");
    Calendar cal = java.util.Calendar.getInstance(locale);
    assertEquals(cal.getCalendarType(), "buddhist", "Unexpected calendar type");

    ThaiBuddhistDate thaiDate = ThaiBuddhistChronology.INSTANCE.date(isoStartDate);

    cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
    cal.set(Calendar.YEAR, thaiDate.get(ChronoField.YEAR));
    cal.set(Calendar.MONTH, thaiDate.get(ChronoField.MONTH_OF_YEAR) - 1);
    cal.set(Calendar.DAY_OF_MONTH, thaiDate.get(ChronoField.DAY_OF_MONTH));

    while (thaiDate.isBefore(isoEndDate)) {
        assertEquals(thaiDate.get(ChronoField.DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + thaiDate + ";  cal: " + cal);
        assertEquals(thaiDate.get(ChronoField.MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + thaiDate);
        assertEquals(thaiDate.get(ChronoField.YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + thaiDate);

        thaiDate = thaiDate.plus(1, ChronoUnit.DAYS);
        cal.add(Calendar.DAY_OF_MONTH, 1);
    }
}
 
Example 8
Source File: DateTimeUtils.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Parses a string using {@link SimpleDateFormat} and a given pattern. This
 * method parses a string at the specified parse position and if successful,
 * updates the parse position to the index after the last character used.
 * The parsing is strict and requires months to be less than 12, days to be
 * less than 31, etc.
 *
 * @param s       string to be parsed
 * @param dateFormat Date format
 * @param tz      time zone in which to interpret string. Defaults to the Java
 *                default time zone
 * @param pp      position to start parsing from
 * @return a Calendar initialized with the parsed value, or null if parsing
 * failed. If returned, the Calendar is configured to the GMT time zone.
 */
private static Calendar parseDateFormat(String s, DateFormat dateFormat,
										TimeZone tz, ParsePosition pp) {
	if (tz == null) {
		tz = DEFAULT_ZONE;
	}
	Calendar ret = Calendar.getInstance(tz, Locale.ROOT);
	dateFormat.setCalendar(ret);
	dateFormat.setLenient(false);

	final Date d = dateFormat.parse(s, pp);
	if (null == d) {
		return null;
	}
	ret.setTime(d);
	ret.setTimeZone(UTC_ZONE);
	return ret;
}
 
Example 9
Source File: JGenProg2017_0013_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void setCalendar(FastDateParser parser, Calendar cal, String value) {
    TimeZone tz;
    if(value.charAt(0)=='+' || value.charAt(0)=='-') {
        tz= TimeZone.getTimeZone("GMT"+value);
    }
    else if(value.startsWith("GMT")) {
        tz= TimeZone.getTimeZone(value);
    }
    else {
        tz= tzNames.get(value);
        if(tz==null) {
            throw new IllegalArgumentException(value + " is not a supported timezone name");
        }
    }
    cal.setTimeZone(tz);
}
 
Example 10
Source File: DateTimeUtils.java    From MongoExplorer with MIT License 5 votes vote down vote up
public static long truncateTime(long value) {
	Calendar cal = Calendar.getInstance();
	cal.setTimeInMillis(value);
	cal.set(Calendar.HOUR_OF_DAY, 0);
	cal.set(Calendar.MINUTE, 0);
	cal.set(Calendar.SECOND, 0);
	cal.set(Calendar.MILLISECOND, 0);
	cal.setTimeZone(TimeZone.getTimeZone("UTC"));
	return cal.getTimeInMillis();
}
 
Example 11
Source File: DateTimeTest.java    From vladmihalcea.wordpress.com with Apache License 2.0 5 votes vote down vote up
private Calendar newCalendarInstanceMillis(String timeZoneId) {
    Calendar calendar = new GregorianCalendar();
    calendar.set(Calendar.YEAR, 1970);
    calendar.set(Calendar.MONTH, 0);
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    calendar.setTimeZone(TimeZone.getTimeZone(timeZoneId));
    return calendar;
}
 
Example 12
Source File: ZonePlayerHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
public void snoozeAlarm(Command command) {
    if (isAlarmRunning() && command instanceof DecimalType) {
        int minutes = ((DecimalType) command).intValue();

        Map<String, String> inputs = new HashMap<String, String>();

        Calendar snoozePeriod = Calendar.getInstance();
        snoozePeriod.setTimeZone(TimeZone.getTimeZone("GMT"));
        snoozePeriod.setTimeInMillis(0);
        snoozePeriod.add(Calendar.MINUTE, minutes);
        SimpleDateFormat pFormatter = new SimpleDateFormat("HH:mm:ss");
        pFormatter.setTimeZone(TimeZone.getTimeZone("GMT"));

        try {
            inputs.put("Duration", pFormatter.format(snoozePeriod.getTime()));
        } catch (NumberFormatException ex) {
            logger.debug("Action Invalid Value Format Exception {}", ex.getMessage());
        }

        Map<String, String> result = service.invokeAction(this, "AVTransport", "SnoozeAlarm", inputs);

        for (String variable : result.keySet()) {
            this.onValueReceived(variable, result.get(variable), "AVTransport");
        }
    } else {
        logger.debug("There is no alarm running on {}", getUDN());
    }
}
 
Example 13
Source File: SolarEventCalculator.java    From Beauty-Compass with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the local rise/set time in the form HH:MM.
 *
 * @param localTimeParam
 *            <code>BigDecimal</code> representation of the local rise/set time.
 * @return <code>Calendar</code> representation of the local time as a calendar, or null for none.
 */
protected Calendar getLocalTimeAsCalendar(BigDecimal localTimeParam, Calendar date) {
    if (localTimeParam == null) {
        return null;
    }

    // Create a clone of the input calendar so we get locale/timezone information.
    Calendar resultTime = (Calendar) date.clone();

    BigDecimal localTime = localTimeParam;
    if (localTime.compareTo(BigDecimal.ZERO) == -1) {
        localTime = localTime.add(BigDecimal.valueOf(24.0D));
        resultTime.add(Calendar.HOUR_OF_DAY, -24);
    }
    String[] timeComponents = localTime.toPlainString().split("\\.");
    int hour = Integer.parseInt(timeComponents[0]);

    BigDecimal minutes = new BigDecimal("0." + timeComponents[1]);
    minutes = minutes.multiply(BigDecimal.valueOf(60)).setScale(0, RoundingMode.HALF_EVEN);
    if (minutes.intValue() == 60) {
        minutes = BigDecimal.ZERO;
        hour += 1;
    }
    if (hour == 24) {
        hour = 0;
    }

    // Set the local time
    resultTime.set(Calendar.HOUR_OF_DAY, hour);
    resultTime.set(Calendar.MINUTE, minutes.intValue());
    resultTime.set(Calendar.SECOND, 0);
    resultTime.set(Calendar.MILLISECOND, 0);
    resultTime.setTimeZone(date.getTimeZone());

    return resultTime;
}
 
Example 14
Source File: SyslogMessageTest.java    From syslog-java-client with MIT License 5 votes vote down vote up
@Test
public void testRfc5424FormatWithStructuredData() throws Exception {
    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(TimeZone.getTimeZone("GMT"));
    cal.set(2013, Calendar.DECEMBER, 5, 10, 30, 5);
    cal.set(Calendar.MILLISECOND, 0);

    System.out.println(SyslogMessage.rfc3339DateFormat.format(cal.getTime()));
    System.out.println(cal.getTimeInMillis());


    SyslogMessage message = new SyslogMessage()
            .withTimestamp(cal.getTimeInMillis())
            .withAppName("my_app")
            .withHostname("myserver.example.com")
            .withFacility(Facility.USER)
            .withSeverity(Severity.INFORMATIONAL)
            .withTimestamp(cal.getTimeInMillis())
            .withMsg("a syslog message")
            .withSDElement(new SDElement("exampleSDID@32473", new SDParam("iut", "3"), new SDParam("eventSource", "Application"), new SDParam("eventID", "1011")));

    String actual = message.toRfc5424SyslogMessage();
    String expected = "<14>1 2013-12-05T10:30:05.000Z myserver.example.com my_app - - [exampleSDID@32473 iut=\"3\" eventSource=\"Application\" eventID=\"1011\"] a syslog message";

    assertThat(actual, is(expected));
    
    message.withSDElement(new SDElement("examplePriority@32473", new SDParam("class", "high")));
    actual = message.toRfc5424SyslogMessage();
    expected = "<14>1 2013-12-05T10:30:05.000Z myserver.example.com my_app - - [exampleSDID@32473 iut=\"3\" eventSource=\"Application\" eventID=\"1011\"][examplePriority@32473 class=\"high\"] a syslog message";
    
    assertThat(actual, is(expected));
}
 
Example 15
Source File: ComplianceController.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the issues exception.
 *
 * @param issuesException the issues exception
 * @return the response entity
 */
@ApiOperation(httpMethod = "POST", value = "Adding issue exception to the corresponding target type")
@RequestMapping(path = "/v2/issue/add-exception", method = RequestMethod.POST)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully Added Issue Exception"),
        @ApiResponse(code = 401, message = "You are not authorized to Add Issue Exception"),
        @ApiResponse(code = 403, message = "Add Issue Exception is forbidden") })
@ResponseBody

public ResponseEntity<Object> addIssuesException(
        @ApiParam(value = "Provide Issue Exception Details", required = true) @RequestBody(required = true) IssuesException issuesException) {
    try {
        
        if (issuesException.getExceptionGrantedDate() == null) {
            return ResponseUtils.buildFailureResponse(new Exception("Exception Granted Date is mandatory"));
        }
        if (issuesException.getExceptionEndDate() == null) {
            return ResponseUtils.buildFailureResponse(new Exception("Exception End Date is mandatory"));
        }
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));
        if(sdf.parse(sdf.format(issuesException.getExceptionGrantedDate())).before(sdf.parse(sdf.format(cal.getTime())))) {
            return ResponseUtils.buildFailureResponse(new Exception("Exception Granted Date cannot be earlier date than today"));
        }
        if(sdf.parse(sdf.format(issuesException.getExceptionEndDate())).before(sdf.parse(sdf.format(cal.getTime())))) {
            return ResponseUtils.buildFailureResponse(new Exception("Exception End Date cannot be earlier date than today"));
        }
        if(issuesException.getIssueIds().isEmpty()) {
            return ResponseUtils.buildFailureResponse(new Exception("Atleast one issue id is required"));
        }
        return ResponseUtils.buildSucessResponse(complianceService.addMultipleIssueException(issuesException));
    } catch (ServiceException | ParseException exception) {
        return ResponseUtils.buildFailureResponse(exception);
    }
}
 
Example 16
Source File: TimeDiff.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Calculate the absolute difference between two Date without regard for
 * time offsets
 * 
 * @param d1 Date one
 * @param d2 Date two
 *
 * @return The fields day, hour, minute, second and millisecond
 */
public static long[] getTimeDifference(Date d1, Date d2) {
	long[] result = new long[5];
	Calendar cal = Calendar.getInstance();
	cal.setTimeZone(TimeZone.getTimeZone("UTC"));
	cal.setTime(d1);

	long t1 = cal.getTimeInMillis();
	cal.setTime(d2);

	long diff = cal.getTimeInMillis() - t1;
	final int ONE_DAY = 1000 * 60 * 60 * 24;
	final int ONE_HOUR = ONE_DAY / 24;
	final int ONE_MINUTE = ONE_HOUR / 60;
	final int ONE_SECOND = ONE_MINUTE / 60;

	long d = diff / ONE_DAY;
	diff %= ONE_DAY;

	long h = diff / ONE_HOUR;
	diff %= ONE_HOUR;

	long m = diff / ONE_MINUTE;
	diff %= ONE_MINUTE;

	long s = diff / ONE_SECOND;
	long ms = diff % ONE_SECOND;
	result[0] = d;
	result[1] = h;
	result[2] = m;
	result[3] = s;
	result[4] = ms;

	return result;
}
 
Example 17
Source File: Dates.java    From boon with Apache License 2.0 5 votes vote down vote up
public static long utcDate( int year, int month, int day ) {
    Calendar calendar = Calendar.getInstance();

    /* Set to midnight. */
    midnight( calendar );

    /* This might change the date, but when you convert it
    back to the clocktime timezone, it will be correct.
     */
    calendar.setTimeZone( UTC_TIME_ZONE );


    return internalDate( year, month, day, calendar );
}
 
Example 18
Source File: SnowflakeDriverIT.java    From snowflake-jdbc with Apache License 2.0 4 votes vote down vote up
/**
 * SNOW-14774: timestamp_ntz value should use client time zone to adjust
 * the epoch time.
 */
@Test
public void testSnow14774() throws Throwable
{
  Connection connection = null;
  Statement statement = null;

  try
  {
    connection = getConnection();

    statement = connection.createStatement();

    // 30 minutes past daylight saving change (from 2am to 3am)
    ResultSet res = statement.executeQuery(
        "select '2015-03-08 03:30:00'::timestamp_ntz");

    res.next();

    // get timestamp in UTC
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    Timestamp tsInUTC = res.getTimestamp(1, calendar);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    String tsStrInUTC = sdf.format(tsInUTC);

    // get timestamp in LA timezone
    calendar.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
    Timestamp tsInLA = res.getTimestamp(1, calendar);

    sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
    String tsStrInLA = sdf.format(tsInLA);

    // the timestamp in LA and in UTC should be the same
    assertEquals("timestamp values not equal", tsStrInUTC, tsStrInLA);

    // 30 minutes before daylight saving change
    res = statement.executeQuery(
        "select '2015-03-08 01:30:00'::timestamp_ntz");

    res.next();

    // get timestamp in UTC
    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
    tsInUTC = res.getTimestamp(1, calendar);

    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    tsStrInUTC = sdf.format(tsInUTC);

    // get timestamp in LA timezone
    calendar.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
    tsInLA = res.getTimestamp(1, calendar);

    sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
    tsStrInLA = sdf.format(tsInLA);

    // the timestamp in LA and in UTC should be the same
    assertEquals("timestamp values not equal", tsStrInUTC, tsStrInLA);
  }
  finally
  {
    closeSQLObjects(null, statement, connection);
  }
}
 
Example 19
Source File: CGMSessionStartTimeDataCallback.java    From Android-BLE-Common-Library with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
	public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
		super.onDataReceived(device, data);

		if (data.size() != 9 && data.size() != 11) {
			onInvalidDataReceived(device, data);
			return;
		}

		final boolean crcPresent = data.size() == 11;
		if (crcPresent) {
			final int actualCrc = CRC16.MCRF4XX(data.getValue(), 0, 9);
			final int expectedCrc = data.getIntValue(Data.FORMAT_UINT16, 9);
			if (actualCrc != expectedCrc) {
				onContinuousGlucoseMonitorSessionStartTimeReceivedWithCrcError(device, data);
				return;
			}
		}

		final Calendar calendar = DateTimeDataCallback.readDateTime(data, 0);
		final Integer timeZoneOffset = TimeZoneDataCallback.readTimeZone(data, 7); // [minutes]
		final DSTOffsetCallback.DSTOffset dstOffset = DSTOffsetDataCallback.readDSTOffset(data, 8);

		if (calendar == null || timeZoneOffset == null || dstOffset == null) {
			onInvalidDataReceived(device, data);
			return;
		}

		final TimeZone timeZone = new TimeZone() {
			@Override
			public int getOffset(final int era, final int year, final int month, final int day, final int dayOfWeek, final int milliseconds) {
				return (timeZoneOffset + dstOffset.offset) * 60000; // convert minutes to milliseconds
			}

			@Override
			public void setRawOffset(final int offsetMillis) {
				throw new UnsupportedOperationException("Can't set raw offset for this TimeZone");
			}

			@Override
			public int getRawOffset() {
				return timeZoneOffset * 60000;
			}

			@Override
			public boolean useDaylightTime() {
				return true;
			}

			@Override
			public boolean inDaylightTime(final Date date) {
				// Use of DST is dependent on the input data only
				return dstOffset.offset > 0;
			}

			@Override
			public int getDSTSavings() {
				return dstOffset.offset * 60000;
			}

			// TODO add TimeZone ID
//			@Override
//			public String getID() {
//				return super.getID();
//			}
		};

		calendar.setTimeZone(timeZone);

		onContinuousGlucoseMonitorSessionStartTimeReceived(device, calendar, crcPresent);
	}
 
Example 20
Source File: EfdcUtils.java    From OpenDA with GNU Lesser General Public License v3.0 3 votes vote down vote up
/**
 * Returns the reference time to use for times in the .INP input files.
 * The times in the .INP input files are relative to a referenceTime.
 * The EFDC model does not use absolute time, it uses only time relative
 * to an arbitrary reference time.
 * This referenceTime can be chosen here, as long as it is
 * applied consistently.
 *
 * @param startTime
 * @param timeZone
 * @return referenceTime.
 */
public static long getReferenceTime(long startTime, TimeZone timeZone) {
    //currently for the EFDC model the reference time is defined
    //so that 1 January 00:00:00 of the year that contains the startTime
    //of the run, corresponds to a time of 1.0 days (see EVENT_TOX2.INP file).
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeZone(timeZone);
    calendar.setTimeInMillis(startTime);
    calendar.set(calendar.get(Calendar.YEAR) - 1, 11, 31, 0, 0, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar.getTimeInMillis();
}