public StringBuffer format(Calendar calendar, StringBuffer buf) { if (mTimeZone != null) { calendar = (Calendar) calendar.clone(); calendar.setTimeZone(mTimeZone); } return applyRules(calendar, buf); }
public static Calendar UTC2Calendar(String dateTime) throws UtilitiesException { Matcher m = UTC_PATTERNER.matcher(dateTime); if (m.matches() && m.groupCount() == 9) { int parts[] = new int[8]; int i; for (i = 0; i < 6; i++) parts[i] = Integer.parseInt(m.group(i + 1)); String ms = m.group(i + 1); if (ms == null) { parts[i++] = 0; } else { if (ms.length() > 3) ms = ms.substring(0, 3); parts[i++] = Integer.parseInt(ms); } String tzStr = m.group(i + 1); TimeZone tz = null; if (tzStr == null || tzStr.equals("Z")) tz = TimeZone.getTimeZone("UTC"); else tz = TimeZone.getTimeZone("GMT" + tzStr); Calendar c = Calendar.getInstance(); c.clear(); c.setTimeZone(tz); c.set(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]); c.add(14, parts[6]); return c; } else { throw new UtilitiesException("Unable to convert datetime to UTC format:" + dateTime); } }
/** * Gets a temporary Calendar set to the specified time zone. The same Calendar is returned on * subsequent calls. */ protected Calendar getCalendar(TimeZone zone) { if (tempCal == null) { tempCal = Calendar.getInstance(zone); } else { tempCal.setTimeZone(zone); } return tempCal; }
/** Returns a new Calendar object which is between start and end */ public static Calendar rand(Calendar start, Calendar end) { if (start.after(end)) { Calendar temp = start; start = end; end = temp; } long diff = end.getTime().getTime() - start.getTime().getTime(); long daysDiff = diff / (1000 * 60 * 60 * 24); int delta = rand(0, (int) daysDiff); Calendar newCal = Calendar.getInstance(); newCal.setTime(start.getTime()); newCal.setTimeZone(start.getTimeZone()); newCal.add(Calendar.DAY_OF_MONTH, delta); newCal.add(Calendar.HOUR, rand(0, 23)); newCal.add(Calendar.MINUTE, rand(0, 59)); newCal.add(Calendar.SECOND, rand(0, 59)); // check range cause we might random picked value // greater than the range. if (newCal.after(end)) { newCal.setTime(end.getTime()); newCal.setTimeZone(end.getTimeZone()); } if (newCal.before(start)) { newCal.setTime(start.getTime()); newCal.setTimeZone(start.getTimeZone()); } return newCal; }
/** * Find the current instance based on effectiveTime (i.e Action_Creation_Time or * Action_Start_Time) * * @return current instance i.e. current(0) returns null if effectiveTime is earlier than Initial * Instance time of the dataset. */ private static Calendar getCurrentInstance(Date effectiveTime, int instanceCount[]) { Date datasetInitialInstance = getInitialInstance(); TimeUnit dsTimeUnit = getDSTimeUnit(); TimeZone dsTZ = getDatasetTZ(); // Convert Date to Calendar for corresponding TZ Calendar current = Calendar.getInstance(); current.setTime(datasetInitialInstance); current.setTimeZone(dsTZ); Calendar calEffectiveTime = Calendar.getInstance(); calEffectiveTime.setTime(effectiveTime); calEffectiveTime.setTimeZone(dsTZ); instanceCount[0] = 0; if (current.compareTo(calEffectiveTime) > 0) { // Nominal Time < initial Instance // TODO: getClass() call doesn't work from static method. // XLog.getLog("CoordELFunction.class").warn("ACTION CREATED BEFORE INITIAL INSTACE "+ // current.getTime()); return null; } Calendar origCurrent = (Calendar) current.clone(); while (current.compareTo(calEffectiveTime) <= 0) { current = (Calendar) origCurrent.clone(); instanceCount[0]++; current.add(dsTimeUnit.getCalendarUnit(), instanceCount[0] * getDSFrequency()); } instanceCount[0]--; current = (Calendar) origCurrent.clone(); current.add(dsTimeUnit.getCalendarUnit(), instanceCount[0] * getDSFrequency()); return current; }
private boolean containsTime(Calendar lookingFor, String[] set) throws ParseException { lookingFor.setTimeZone(TimeZone.getTimeZone("GMT")); Date lookingForDate = lookingFor.getTime(); for (String s : set) { // System.out.println( "contsinsCalendar: " + lookingFor + " " + set[i] ); Calendar toMatch = EC2RestAuth.parseDateString(s); toMatch.setTimeZone(TimeZone.getTimeZone("GMT")); Date toMatchDate = toMatch.getTime(); if (0 == lookingForDate.compareTo(toMatchDate)) return true; } return false; }
@TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "setTimeZone", args = {java.util.TimeZone.class}) public void test_setTimeZoneLjava_util_TimeZone() { Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone("GMT-6")); assertEquals(TimeZone.getTimeZone("GMT-6"), cal.getTimeZone()); cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-8")); cal.setTimeZone(TimeZone.getTimeZone("GMT-6")); assertEquals(TimeZone.getTimeZone("GMT-6"), cal.getTimeZone()); cal.setTimeZone(null); }
public static String getWeek(int num, String format) { final Calendar c = Calendar.getInstance(); c.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); int weekNum = c.get(Calendar.DAY_OF_WEEK) + num; if (weekNum > 7) weekNum = weekNum - 7; return format + WEEK[weekNum - 1]; }
/** * Get a Calendar instance for current thread. * * @return A Calendar instance for current thread. */ private static Calendar getCalendar() { // We have to reset the time zone each time in case the result set // implementation changes it. Calendar calendar = THREAD_SAFE_CALENDAR.get(); calendar.setTimeZone(TIME_ZONE); return calendar; }
private void getUsageInfo() { final Calendar now = Calendar.getInstance(); final Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(Calendar.YEAR, now.get(Calendar.YEAR)); cal.set(Calendar.MONTH, now.get(Calendar.MONTH)); final int dayMin = now.getActualMinimum(Calendar.DAY_OF_MONTH); final int dayMax = now.getActualMaximum(Calendar.DAY_OF_MONTH); cal.set(Calendar.DAY_OF_MONTH, dayMin); cal.setTimeZone(now.getTimeZone()); final Date start = cal.getTime(); cal.set(Calendar.DAY_OF_MONTH, dayMax); cal.add(Calendar.DATE, 1); final Date end = cal.getTime(); final TaskRunnable<Object[], NetworkUsageInfo, NetworkUsageSummaryPreferences> task; task = new TaskRunnable<Object[], NetworkUsageInfo, NetworkUsageSummaryPreferences>() { @Override public NetworkUsageInfo doLongOperation(Object[] params) throws InterruptedException { final int[] network = {ConnectivityManager.TYPE_MOBILE}; return NetworkUsageInfo.get( (Context) params[0], (Date) params[1], (Date) params[2], dayMin, dayMax, network); } @Override public void callback(NetworkUsageSummaryPreferences handler, NetworkUsageInfo result) { handler.setUsage(result); } }; task.setResultHandler(this); task.setParams(new Object[] {getContext(), start, end}); AsyncManager.runBackgroundTask(task); }
/** * Get the next {@link Date} in the sequence matching the Cron pattern and after the value * provided. The return value will have a whole number of seconds, and will be after the input * value. * * @param date a seed value * @return the next value matching the pattern */ public Date next(Date date) { /* The plan: 1 Round up to the next whole second 2 If seconds match move on, otherwise find the next match: 2.1 If next match is in the next minute then roll forwards 3 If minute matches move on, otherwise find the next match 3.1 If next match is in the next hour then roll forwards 3.2 Reset the seconds and go to 2 4 If hour matches move on, otherwise find the next match 4.1 If next match is in the next day then roll forwards, 4.2 Reset the minutes and seconds and go to 2 ... */ Calendar calendar = new GregorianCalendar(); calendar.setTimeZone(this.timeZone); calendar.setTime(date); // First, just reset the milliseconds and try to calculate from there... calendar.set(Calendar.MILLISECOND, 0); long originalTimestamp = calendar.getTimeInMillis(); doNext(calendar, calendar.get(Calendar.YEAR)); if (calendar.getTimeInMillis() == originalTimestamp) { // We arrived at the original timestamp - round up to the next whole second and try again... calendar.add(Calendar.SECOND, 1); doNext(calendar, calendar.get(Calendar.YEAR)); } return calendar.getTime(); }
public void testCalendar() { kryo.setRegistrationRequired(false); Calendar calendar = Calendar.getInstance(); calendar.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); calendar.set(1980, 7, 26, 12, 22, 46); roundTrip(64, calendar); }
public int obtenerDiasHabiles(Date fecha, Date fecha2) { Calendar calendario = Calendar.getInstance(); calendario.setTimeZone(TimeZone.getTimeZone("GMT-4:00")); calendario.setTime(fecha2); calendario.add(Calendar.DAY_OF_YEAR, +1); calendario.set(Calendar.HOUR, 0); calendario.set(Calendar.HOUR_OF_DAY, 0); calendario.set(Calendar.SECOND, 0); calendario.set(Calendar.MILLISECOND, 0); calendario.set(Calendar.MINUTE, 0); fecha2 = calendario.getTime(); calendario.setTime(fecha); String fija = formatoFecha.format(fecha2); String hoy = ""; int contador = 0; do { calendario.setTime(fecha); if (calendario.get(Calendar.DAY_OF_WEEK) != 1 && calendario.get(Calendar.DAY_OF_WEEK) != 7) contador++; calendario.add(Calendar.DAY_OF_YEAR, +1); fecha = calendario.getTime(); hoy = formatoFecha.format(fecha); } while (!hoy.equals(fija)); return contador; }
private void initView() { new timeThread().start(); Calendar c = Calendar.getInstance(); c.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); date.setText( String.valueOf(c.get(Calendar.MONTH) + 1) + "月" + String.valueOf(c.get(Calendar.DAY_OF_MONTH)) + "日"); String mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK)); if ("1".equals(mWay)) { mWay = "天"; } else if ("2".equals(mWay)) { mWay = "一"; } else if ("3".equals(mWay)) { mWay = "二"; } else if ("4".equals(mWay)) { mWay = "三"; } else if ("5".equals(mWay)) { mWay = "四"; } else if ("6".equals(mWay)) { mWay = "五"; } else if ("7".equals(mWay)) { mWay = "六"; } week.setText("星期" + mWay); }
@Test public void testSerializeCalendar() throws Exception { int year = 1990; int month = 11; int day = 15; int hour = 10; int minute = 50; int seconds = 30; int milliseconds = 123; Calendar calendar = Calendar.getInstance(); calendar.setTimeZone(TimeZone.getTimeZone("UTC")); calendar.set(year, month - 1, day, hour, minute, seconds); calendar.set(Calendar.MILLISECOND, milliseconds); CalendarSerializer calendarSerializer = new CalendarSerializer(); String strDate = calendarSerializer.serialize(calendar, Calendar.class, null).toString(); // yyyy-MM-dd'T'HH:mm:ss'.'SSS'Z String expectedDate = String.format( "\"%s-%d-%sT%s:%s:%s.%sZ\"", year, month, day, hour, minute, seconds, milliseconds); assertEquals(expectedDate, strDate); }
public void testToCalendarWithGYearMonth() { Calendar controlCalendar = Calendar.getInstance(); controlCalendar.clear(); controlCalendar.set(Calendar.YEAR, 2001); controlCalendar.set(Calendar.MONTH, 4); controlCalendar.setTimeZone(TimeZone.getTimeZone("GMT")); Calendar aCalendar = dataHelper.toCalendar("2001-05"); assertTrue( "Expected YEAR: " + controlCalendar.get(Calendar.YEAR) + ", but was: " + aCalendar.get(Calendar.YEAR), controlCalendar.get(Calendar.YEAR) == aCalendar.get(Calendar.YEAR)); assertTrue( "Expected MONTH: " + controlCalendar.get(Calendar.MONTH) + ", but was: " + aCalendar.get(Calendar.MONTH), controlCalendar.get(Calendar.MONTH) == aCalendar.get(Calendar.MONTH)); assertTrue( "Expected TimeZone: " + controlCalendar.getTimeZone() + ", but was: " + aCalendar.getTimeZone(), controlCalendar.getTimeZone().equals(aCalendar.getTimeZone())); assertTrue( "Expected same time in millis", controlCalendar.getTimeInMillis() == aCalendar.getTimeInMillis()); }
@Test public void testDeserializeCalendar() throws Exception { String strDate = "1990-11-15T10:50:30.123Z"; CalendarSerializer calendarSerializer = new CalendarSerializer(); Calendar calendar = calendarSerializer.deserialize(new JsonPrimitive(strDate), Calendar.class, null); int year = 1990; int month = 11; int day = 15; int hour = 10; int minute = 50; int seconds = 30; int milliseconds = 123; calendar.setTimeZone(TimeZone.getTimeZone("UTC")); assertEquals(year, calendar.get(Calendar.YEAR)); assertEquals(month - 1, calendar.get(Calendar.MONTH)); assertEquals(day, calendar.get(Calendar.DAY_OF_MONTH)); assertEquals(hour, calendar.get(Calendar.HOUR_OF_DAY)); assertEquals(minute, calendar.get(Calendar.MINUTE)); assertEquals(seconds, calendar.get(Calendar.SECOND)); assertEquals(milliseconds, calendar.get(Calendar.MILLISECOND)); }
@Override public void onVisibilityChanged(boolean visible) { Log.d(TAG, "onVisibilityChanged: " + visible); super.onVisibilityChanged(visible); if (visible) { mGoogleApiClient.connect(); registerReceiver(); // Update time zone and date formats, in case they changed while we weren't visible. mCalendar.setTimeZone(TimeZone.getDefault()); } else { unregisterReceiver(); if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } } // Whether the timer should be running depends on whether we're visible (as well as // whether we're in ambient mode), so we may need to start or stop the timer. updateTimer(); }
public void testToCalendarWithGMonthDay() { Calendar controlCalendar = Calendar.getInstance(); controlCalendar.clear(); controlCalendar.set(Calendar.MONTH, 11); controlCalendar.set(Calendar.DATE, 4); controlCalendar.setTimeZone(TimeZone.getTimeZone("GMT")); Calendar aCalendar = dataHelper.toCalendar("--12-04"); assertTrue( "Expected MONTH: " + controlCalendar.get(Calendar.MONTH) + ", but was: " + aCalendar.get(Calendar.MONTH), controlCalendar.get(Calendar.MONTH) == aCalendar.get(Calendar.MONTH)); assertTrue( "Expected DATE: " + controlCalendar.get(Calendar.DATE) + ", but was: " + aCalendar.get(Calendar.DATE), controlCalendar.get(Calendar.DATE) == aCalendar.get(Calendar.DATE)); assertTrue( "Expected TimeZone: " + controlCalendar.getTimeZone() + ", but was: " + aCalendar.getTimeZone(), controlCalendar.getTimeZone().equals(aCalendar.getTimeZone())); assertTrue( "Expected same time in millis", controlCalendar.getTimeInMillis() == aCalendar.getTimeInMillis()); }
protected String getFormattedTime() { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.setTimeZone(TimeZone.getDefault()); SimpleDateFormat d = new SimpleDateFormat("hh:mm"); return d.format(calendar.getTime()); }
void populateStartDate() throws SQLException, Exception { startDateS.removeActionListener(this); startDateS.removeAllItems(); dateRange.clear(); if (sourceTable.sourceListModel.isSelectionEmpty() == false && sourceTable.getValueAt(sourceTable.getSelectedRow(), 0).toString() != null) { Statement MySQL_Statement = dbConn.createStatement(); String getMinMaxSQL = "SELECT UNIX_TIMESTAMP(DATE_ADD(DATE(MIN(date_time)),INTERVAL 1 DAY)) AS min_date,UNIX_TIMESTAMP(DATE(MAX(date_time))) AS max_date FROM data_sa WHERE site_id = " + siteTable.getValueAt(siteTable.getSelectedRow(), 0) + " AND source_id = " + sourceTable.getValueAt(sourceTable.getSelectedRow(), 0); ResultSet minMaxResults = MySQL_Statement.executeQuery(getMinMaxSQL); if (minMaxResults.next()) { Calendar minCal = Calendar.getInstance(); minCal.setTimeZone(TimeZone.getTimeZone("GMT+10")); minCal.setTimeInMillis(minMaxResults.getLong("min_date") * 1000); long maxCal = minMaxResults.getLong("max_date") * 1000; while (minCal.getTimeInMillis() <= maxCal) { dateRange.add(minCal.getTimeInMillis()); startDateS.addItem(dateFormatter.format(minCal.getTimeInMillis())); minCal.add(Calendar.DATE, 1); } startDateS.setEnabled(true); populateEndDate(); } else { throw new Exception("ERR:NoData"); } } else { // This should never be able to happen throw new Exception("NoSource"); } startDateS.addActionListener(this); }
public static void main(String[] args) throws ParseException { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a"); String dateInString = "2015-12-10 04:52:30 下午"; Date date = formatter.parse(dateInString); TimeZone tz = TimeZone.getDefault(); // From TimeZone Asia/Shanghai System.out.println("TimeZone: " + tz.getID() + "-" + tz.getDisplayName()); System.out.println("TimeZone: " + tz); System.out.println("Date: " + formatter.format(date)); // To TimeZone America/New_York SimpleDateFormat sdfAmerica = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a"); TimeZone tzInAmerica = TimeZone.getTimeZone("America/New_York"); sdfAmerica.setTimeZone(tzInAmerica); Calendar calendar = new GregorianCalendar(); // System.out.println("\nAmericaTimeZone: " // +tzInAmerica.getID()+"-"+tzInAmerica.getDisplayName()); // System.out.println("AmericaTimeZone: " +tzInAmerica); // System.out.println("Date+Formatter: " +sdfAmerica.format(calendar.getTime())); calendar.setTime(date); calendar.setTimeZone(tzInAmerica); System.out.println(calendar.get(Calendar.YEAR)); System.out.println(calendar.get(Calendar.AM_PM)); }
public TableModel produce(final DataRow parameters, final DataFactoryContext dataFactoryContext) throws ReportDataFactoryException { final int limit = getTypedParameter("limit", Integer.class, 100); final long seed = getTypedParameter("seed", Long.class, System.currentTimeMillis()); final TypedTableModel model = new TypedTableModel(); model.addColumn("rowcount", Integer.class); model.addColumn("integer", Integer.class); model.addColumn("double", Double.class); model.addColumn("text", String.class); model.addColumn("text2", String.class); model.addColumn("date", Date.class); final Random random = new Random(); random.setSeed(seed); final Calendar baseDate = new GregorianCalendar(2000, 1, 1); baseDate.setTimeZone(TimeZone.getTimeZone("UTC")); final long millis = baseDate.getTimeInMillis(); for (int i = 0; i < limit; i++) { model.addRow( i, (int) (random.nextDouble() * Integer.MAX_VALUE) - (Integer.MAX_VALUE / 2), random.nextDouble() * Integer.MAX_VALUE, "Some Text with breaks " + i, "SomeTextWithoutBreaks" + i, new Date(millis + (long) (200 * random.nextDouble() * Integer.MAX_VALUE))); } return model; }
@TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "toString", args = {}) public void test_toString() { Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); cal1.setTimeZone(TimeZone.getTimeZone("GMT-6")); cal2.setTimeZone(TimeZone.getTimeZone("GMT-8")); cal1.set(Calendar.MILLISECOND, 0); cal2.set(Calendar.MILLISECOND, 0); assertFalse(cal1.toString().equals(cal2.toString())); cal1.setTimeZone(TimeZone.getTimeZone("GMT-8")); assertTrue(cal1.toString().equals(cal2.toString())); }
static { Calendar c = Calendar.getInstance(); c.setTimeZone(TimeZone.getTimeZone("GMT")); // $NON-NLS-1$ c.set(1900, 0, 1, 0, 0, 0); c.set(Calendar.MILLISECOND, 0); DATE_NORMALIZER = -(int) (c.getTime().getTime() / 60000); // support a 32 bit range starting at this value }
public static String getTomorrowDate() { Calendar calendar = Calendar.getInstance(); calendar.setTimeZone(TimeZone.getTimeZone(timeZone)); calendar.setTime(new Date()); calendar.add(Calendar.DATE, 1); String strDate = formatCalendar(calendar); return strDate; }
/** * get calendar by user setting (timezone, first day of week) * * @param calendarSetting * @return calendar object */ public static Calendar getCalendarInstanceBySetting(CalendarSetting calendarSetting) { Calendar calendar = GregorianCalendar.getInstance(); calendar.setLenient(false); calendar.setTimeZone(TimeZone.getTimeZone(calendarSetting.getTimeZone())); calendar.setFirstDayOfWeek(Integer.parseInt(calendarSetting.getWeekStartOn())); calendar.setMinimalDaysInFirstWeek(4); return calendar; }
@Override public void setUp() { Calendar cal = new GregorianCalendar(2007, 8 - 1, 13, 19, 51, 23); cal.setTimeZone(TimeZone.getTimeZone("GMT")); cal.set(Calendar.MILLISECOND, 0); date = cal.getTime(); df = new ISO8601DateFormat(); }
private Date getNewDate(int increment) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); Calendar c = Calendar.getInstance(); c.setTimeZone(TimeZone.getTimeZone("GMT")); c.setTime(sdf.parse(START_DATE)); c.add(Calendar.DATE, increment); return c.getTime(); }
@AuraEnabled public Calendar getCalendarWithTimeZoneLater() { Calendar c = Calendar.getInstance(); c.set(2006, 6, 4, 16, 30, 0); c.set(Calendar.MILLISECOND, 0); c.setTimeZone(TimeZone.getTimeZone("GMT")); return c; }