private void InitState() { // title String sSubTitle = utils.GetResStr(R.string.titleDefaultAppointment); // date values dateStart = Calendar.getInstance(); dateEndOn = Calendar.getInstance(); dataRow.SetDuration(prefs.iMinutesDuration); // INSERT MODE if (GetStartMode() == StartMode.NEW) { sSubTitle = utils.GetResStr(R.string.titleNewAppointment); btnDelete.setVisibility(View.INVISIBLE); // initialize data SetStartDateByAgendaView(dateStart); updateStartDateTimeForNewAppointment(dateStart); SetStartTimeForDayAgendaView(dateStart); chkAllDay.setChecked(false); chkAlarm.setChecked(true); // repeat data iRepeatType = 0; // none iRepeatEvery = 1; dateEndOn.setTimeInMillis(0); // no end date } // EDIT MODE if (GetStartMode() == StartMode.EDIT) { sSubTitle = utils.GetResStr(R.string.titleEditAppointment); dateStart.setTimeInMillis(dataRow.GetStartDate().getTimeInMillis()); btnDelete.setVisibility(View.VISIBLE); edSubject.setText(dataRow.GetSubject()); chkAllDay.setChecked(dataRow.GetAllDay()); chkAlarm.setChecked(dataRow.GetAlarm()); // repeat data iRepeatType = dataRow.GetRepeat().GetRepeatTypeAsInt(); iRepeatEvery = dataRow.GetRepeat().GetEvery(); dateEndOn.setTimeInMillis(dataRow.GetRepeat().GetEndOnDate().getTimeInMillis()); } restoreStateFromFreezeIfRequired(); SetActivityTitle(sSubTitle); UpdateStartDateTimeView(); UpdateRepeatInfo(); // set focus to subject edSubject.requestFocus(); if (GetStartMode() == StartMode.EDIT) edSubject.setSelection(edSubject.length()); }
/** * Convert the string input param value to its typed object value. * * @param value The string value of the input param * @param type The type of the input value, defined at DBConstants.DataTypes. * @return The typed object value of the input param */ public static Object convertInputParamValue(String value, String type) throws DataServiceFault { try { if (DBConstants.DataTypes.INTEGER.equals(type)) { return Integer.parseInt(value); } else if (DBConstants.DataTypes.LONG.equals(type)) { return Long.parseLong(value); } else if (DBConstants.DataTypes.FLOAT.equals(type)) { return Float.parseFloat(value); } else if (DBConstants.DataTypes.DOUBLE.equals(type)) { return Double.parseDouble(value); } else if (DBConstants.DataTypes.BOOLEAN.equals(type)) { return Boolean.parseBoolean(value); } else if (DBConstants.DataTypes.DATE.equals(type)) { return new java.util.Date(DBUtils.getDate(value).getTime()); } else if (DBConstants.DataTypes.TIME.equals(type)) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(DBUtils.getTime(value).getTime()); return cal; } else if (DBConstants.DataTypes.TIMESTAMP.equals(type)) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(DBUtils.getTimestamp(value).getTime()); return cal; } else { return value; } } catch (Exception e) { throw new DataServiceFault(e); } }
public static Date OmDateTimeUnpack(long value, int fractional) { if (value == OM_DATETIME_ZERO) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(0); return cal.getTime(); } if (value >= OM_DATETIME_INFINITE || value < 0) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(Long.MAX_VALUE); return cal.getTime(); } try { Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(Calendar.YEAR, OM_DATETIME_YEAR(value)); cal.set(Calendar.MONTH, OM_DATETIME_MONTH(value) - 1); cal.set(Calendar.DAY_OF_MONTH, OM_DATETIME_DAY(value)); cal.set(Calendar.HOUR_OF_DAY, OM_DATETIME_HOURS(value)); cal.set(Calendar.MINUTE, OM_DATETIME_MINUTES(value)); cal.set(Calendar.SECOND, OM_DATETIME_SECONDS(value)); cal.set(Calendar.MILLISECOND, 1000 * fractional / 0x10000); return cal.getTime(); } catch (Exception e) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(0); return cal.getTime(); } }
@Test public void testDateEffectiveExpires() { WorkingMemory wm = new KnowledgeBaseImpl("x", null).newStatefulSession(); final RuleImpl rule = new RuleImpl("myrule"); final Calendar past = Calendar.getInstance(); past.setTimeInMillis(10); final Calendar future = Calendar.getInstance(); future.setTimeInMillis(future.getTimeInMillis() + 100000000); rule.setDateEffective(past); rule.setDateExpires(future); assertTrue(rule.isEffective(null, new RuleTerminalNode(), wm)); rule.setDateExpires(past); assertFalse(rule.isEffective(null, new RuleTerminalNode(), wm)); rule.setDateExpires(future); rule.setDateEffective(future); assertFalse(rule.isEffective(null, new RuleTerminalNode(), wm)); }
/** * Returns {@code true} if the end date occurs after the start date during the period of time * represented by this time span. */ public boolean insideRange(long startDate, long endDate) { Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.setTimeInMillis(startDate); c2.setTimeInMillis(endDate); return isInRange(c1, c2); }
/** * O método readObject retorna o objeto em que o ponteiro do arquivo está posicionado. O método * dispara a seguinte exceção: * * @exception IOException caso não seja possível recuperar o objeto do arquivo. * @return um <code>Despesa</code> com os dados lidos do arquivo. */ @Override public Despesa readObject() throws IOException { Despesa despesa = new Despesa(); despesa.setCodigo(arquivoBinario.readInt()); despesa.setCodigoCategoria(arquivoBinario.readInt()); despesa.setCodigoPagamento(arquivoBinario.readInt()); Calendar calDes = Calendar.getInstance(); calDes.setTimeInMillis(arquivoBinario.readLong()); despesa.setDataDespesa(calDes); calDes.setTimeInMillis(arquivoBinario.readLong()); despesa.setDataPagamento(calDes); despesa.setDescricao(readString(40, true)); despesa.setValorDespesa(arquivoBinario.readDouble()); despesa.setNumeroParcelas(arquivoBinario.readInt()); despesa.setNumeroCheque(readString(20, true)); return despesa; } // readObject()
/**根据数据范围计算时间轴刻度 * <pre> * 单位刻度:一天 * 最多刻度数量:7个 * <1天:(step:1)0,1 * <=7天:(step:1)1,2,3,4,5,6,7 * 8天:(step:2)1,3,5,7,9 * 29天:(step:5)1,6,11,16,21,26,31 * >月:(月) * 3个月:(step:15)1,16,31,56,71,96,111 或者(step:月):1,2,3 * 大于年:(step:n年) * * * @param start 数据起始位置 * @param end 数据结束位置 * @param scaleBase 单位刻度 * @param isRound 边缘是否按整刻度 * @param maxScales 最多刻度数量 * @return */ public static long[] getListTime_scale( long start, long end, long scaleBase, boolean isRound, int maxScales) { long datas[]; long dataArea = end - start; int stepField = getDateField(dataArea); long step = (dataArea) / maxScales; if (step < scaleBase) { step = scaleBase; } long fieldValue = getDateFieldInMillis(stepField); step = (step + fieldValue - 1) / fieldValue; datas = new long[(int) ((dataArea + fieldValue * step - 1) / (fieldValue * step))]; // System.out.println("stepField "+ stepField+" fieldValue " +fieldValue+ " step: "+step); Calendar fromCalendar = Calendar.getInstance(); Calendar toCalcendar = Calendar.getInstance(); fromCalendar.setTimeInMillis(start); toCalcendar.setTimeInMillis(end); for (int i = 0; fromCalendar.before(toCalcendar); ++i, fromCalendar.set(stepField, (int) (fromCalendar.get(stepField) + step))) { datas[i] = fromCalendar.getTimeInMillis(); // System.out.println(formatter.format(fromCalendar.getTimeInMillis())); } // System.out.println("date:"+formatter.format(fromCalendar.getTimeInMillis())); return datas; }
public void createCalendar() { List<Service> services = db.getCalendars(); Calendar start = null; Calendar end = null; int doyStart, doyEnd, dow = -1; int[] validityVector = null; boolean[] validity = null; String dbVector = null; for (Service s : services) { start = new GregorianCalendar(); end = new GregorianCalendar(); start.setFirstDayOfWeek(Calendar.MONDAY); end.setFirstDayOfWeek(Calendar.MONDAY); validityVector = new int[366]; dbVector = new String(); for (int i = 0; i < 366; i++) validityVector[i] = 0; start.setTimeInMillis(parseDateToMillis(s.getStartDate())); end.setTimeInMillis(parseDateToMillis(s.getEndDate())); doyStart = start.get(Calendar.DAY_OF_YEAR); doyEnd = end.get(Calendar.DAY_OF_YEAR); validity = s.getValidity(); Calendar c = (Calendar) start.clone(); while (doyStart <= doyEnd) { dow = c.get(Calendar.DAY_OF_WEEK); if (validity[dow - 1]) validityVector[doyStart - 1] = 1; c.add(Calendar.DAY_OF_YEAR, +1); doyStart = c.get(Calendar.DAY_OF_YEAR); } for (int i = 0; i < 366; i++) dbVector += validityVector[i]; db.insertService(s.getId(), s.getStartDate(), s.getEndDate(), dbVector, city); } }
/** * Builds the HTML code for a select box of months. * * <p> * * @param timeMillis the time in milliseconds which should be preselected * @param fieldName the prefix of the name attribute * @param attributes optional additional attributes of the select tag * @param localeString the current locale String * @return the HTML code for a select box of months */ public static String buildSelectMonth( long timeMillis, String fieldName, String attributes, String localeString) { StringBuffer retValue = new StringBuffer(512); Locale locale = new Locale(localeString); Calendar cal = new GregorianCalendar(locale); cal.setTimeInMillis(timeMillis); Calendar calTemp = new GregorianCalendar(locale); calTemp.setTimeInMillis(timeMillis); // set day to 2 to avoid display errors for days 29, 30 and 31 calTemp.set(Calendar.DAY_OF_MONTH, 2); DateFormat df = new SimpleDateFormat("MMMM", locale); retValue.append("<select name=\"" + fieldName + "month\""); if (attributes != null) { retValue.append(" " + attributes); } retValue.append(">\n"); for (int i = 0; i < 12; i++) { calTemp.set(Calendar.MONTH, i); retValue.append("\t<option value=\"" + (i + 1) + "\""); if (cal.get(Calendar.MONTH) == i) { retValue.append(" selected=\"selected\""); } retValue.append(">" + df.format(calTemp.getTime()) + "</option>\n"); } retValue.append("</select>\n"); return retValue.toString(); }
/** Make an update for the daily/weekly/last kill & ap counts */ public void doUpdate() { boolean needUpdate = false; Calendar lastCal = Calendar.getInstance(); lastCal.setTimeInMillis(lastUpdate); Calendar curCal = Calendar.getInstance(); curCal.setTimeInMillis(System.currentTimeMillis()); // Checking the day - month & year are checked to prevent if a player come back after 1 month, // the same day if (lastCal.get(Calendar.DAY_OF_MONTH) != curCal.get(Calendar.DAY_OF_MONTH) || lastCal.get(Calendar.MONTH) != curCal.get(Calendar.MONTH) || lastCal.get(Calendar.YEAR) != curCal.get(Calendar.YEAR)) { this.dailyAP = 0; this.dailyKill = 0; needUpdate = true; } // Checking the week - year is checked to prevent if a player come back after 1 year, the same // week if (lastCal.get(Calendar.WEEK_OF_YEAR) != curCal.get(Calendar.WEEK_OF_YEAR) || lastCal.get(Calendar.YEAR) != curCal.get(Calendar.YEAR)) { this.lastKill = this.weeklyKill; this.lastAP = this.weeklyAP; this.weeklyKill = 0; this.weeklyAP = 0; needUpdate = true; } // Finally, update the the last update this.lastUpdate = System.currentTimeMillis(); if (needUpdate) setPersistentState(PersistentState.UPDATE_REQUIRED); }
@Test public void testMapping() throws Exception { final Logger logger = EasyMock.createNiceMock(Logger.class); EasyMock.replay(logger); final TimeZoneUtil timeZoneUtil = new TimeZoneUtilImpl(); final CurrentTime currentTime = new CurrentTimeImpl(); final ParseUtil parseUtil = new ParseUtilImpl(); final CalendarUtil calendarUtil = new CalendarUtilImpl(logger, currentTime, parseUtil, timeZoneUtil); final MapperCalendar mapperCalendar = new MapperCalendar(timeZoneUtil, calendarUtil, parseUtil); final MapperCalendarFixLength mapperCalendarFixLength = new MapperCalendarFixLength(mapperCalendar, calendarUtil); { final Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(1l); assertEquals("0000000000000000001", mapperCalendarFixLength.toString(calendar)); } { final Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(Long.MAX_VALUE); assertEquals(String.valueOf(Long.MAX_VALUE), mapperCalendarFixLength.toString(calendar)); } { assertEquals(1l, mapperCalendarFixLength.fromString(String.valueOf(1l)).getTimeInMillis()); } { assertEquals( Long.MAX_VALUE, mapperCalendarFixLength.fromString(String.valueOf(Long.MAX_VALUE)).getTimeInMillis()); } }
/** * 按周获得某几周周一 00:00:00 到周六 的时间范围 * * <p>它会根据给定的 offL 和 offR 得到一个时间范围 * * <p>对本函数来说 week(-3,-5) 和 week(-5,-3) 是一个意思 * * @param base 基础时间,毫秒 * @param offL 从本周偏移几周, 0 表示本周,-1 表示上一周,1 表示下一周 * @param offR 从本周偏移几周, 0 表示本周,-1 表示上一周,1 表示下一周 * @return 时间范围(毫秒级别) */ public static Date[] weeks(long base, int offL, int offR) { int from = Math.min(offL, offR); int len = Math.abs(offL - offR); // 现在 Calendar c = Calendar.getInstance(); c.setTimeInMillis(base); Date[] re = new Date[2]; // 计算开始 c.setTimeInMillis(c.getTimeInMillis() + MS_WEEK * from); c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); re[0] = c.getTime(); // 计算结束 c.setTimeInMillis(c.getTimeInMillis() + MS_WEEK * (len + 1) - 1000); c.set(Calendar.HOUR_OF_DAY, 23); c.set(Calendar.MINUTE, 59); c.set(Calendar.SECOND, 59); re[1] = c.getTime(); // 返回 return re; }
protected static String getTimeAgoString( Locale locale, long timestamp, boolean isMultiple, TimeAgoType timeAgoType) { if (timeAgoType == TimeAgoType.DIFF) { long now = System.currentTimeMillis(); float diff = now - timestamp; String stime = getShortTimestamp(diff); return stime; } else { if (timeAgoType == TimeAgoType.PREFER_DATE_TIME && !isMultiple) { return getBuildTimeString(timestamp, locale, true, true, true); } else { Calendar nowCal = Calendar.getInstance(); nowCal.setTimeInMillis(System.currentTimeMillis()); Calendar thenCal = Calendar.getInstance(); thenCal.setTimeInMillis(timestamp); int nowDay = nowCal.get(Calendar.DAY_OF_YEAR); int thenDay = thenCal.get(Calendar.DAY_OF_YEAR); boolean isToday = (nowDay == thenDay); if (isToday) { return getBuildTimeString(timestamp, locale, false, true, false); } else { return getBuildTimeString(timestamp, locale, true, false, false); } } } }
public static java.util.Date addMonths(Comparable<?> param1, Comparable<?> param2, Calendar cal) throws ParseException { if (param1 == null && param2 == null) { return null; } try { int months = getInteger(param2); if (param1 instanceof Timestamp) { Timestamp d = (Timestamp) param1; cal.setTimeInMillis(d.getTime()); cal.add(Calendar.MONTH, months); return new Timestamp(cal.getTimeInMillis()); } else if (param1 instanceof java.sql.Date) { java.util.Date d = (java.util.Date) param1; cal.setTimeInMillis(d.getTime()); cal.add(Calendar.MONTH, months); return new java.util.Date(cal.getTimeInMillis()); } else { throw new ParseException(); } } catch (ParseException e) { throw new ParseException( WRONG_TYPE + " month_between(" + param1.getClass() + "," + param2.getClass() + ")"); } }
public Date getHistoryEndDate() { if (m_customEnd != null) { try { if (m_customEnd.length() == 8) { return m_dayFormat.parse(m_customEnd); } else if (m_customEnd.length() == 10) { return m_hourlyFormat.parse(m_customEnd); } } catch (ParseException e) { } } long temp = 0; Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(m_date); if ("month".equals(m_reportType)) { int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH); temp = m_date + maxDay * (TimeHelper.ONE_HOUR * 24); } else if ("week".equals(m_reportType)) { temp = m_date + 7 * (TimeHelper.ONE_HOUR * 24); } else { temp = m_date + (TimeHelper.ONE_HOUR * 24); } cal.setTimeInMillis(temp); return cal.getTime(); }
@Override public void bindView(View view, Context context, Cursor cursor) { super.bindView(view, context, cursor); TextView setup = (TextView) view.findViewById(R.id.text3); TextView reply = (TextView) view.findViewById(R.id.text4); locationCursor.moveToPosition(cursor.getPosition()); long rt = locationCursor.getLong(1); if (rt > 0) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(rt); DateFormat sdf = SimpleDateFormat.getDateTimeInstance(); setup.setText("requested on: " + sdf.format(cal.getTime())); } else { setup.setText("requested on: <not available>"); } rt = locationCursor.getLong(2); if (rt > 0) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(rt); DateFormat sdf = SimpleDateFormat.getDateTimeInstance(); reply.setText("updated on:" + sdf.format(cal.getTime())); ((ImageView) view.findViewById(R.id.status)) .setImageResource(android.R.drawable.presence_online); } else { reply.setText("updated on: <not available>"); } }
public UDFImageBuilderFile(File sourceFile) throws Exception { childs = new ArrayList<UDFImageBuilderFile>(); identifier = sourceFile.getName(); this.sourceFile = sourceFile; // TODO: better way to get real access time AccessTime = Calendar.getInstance(); // TODO: better way to get real attribute time AttributeTime = Calendar.getInstance(); AttributeTime.setTimeInMillis(sourceFile.lastModified()); // TODO: better way to get real creation time CreationTime = Calendar.getInstance(); CreationTime.setTimeInMillis(sourceFile.lastModified()); ModificationTime = Calendar.getInstance(); ModificationTime.setTimeInMillis(sourceFile.lastModified()); if (sourceFile.isDirectory()) { fileType = FileType.Directory; File childFiles[] = sourceFile.listFiles(); for (int i = 0; i < childFiles.length; ++i) { addChild(childFiles[i]); } } else { fileType = FileType.File; } }
private boolean inSameAggregationPeriod(Datapoint d1, Datapoint d2) { if (d1 == null || d2 == null) return false; mCal1.setTimeInMillis(d1.mMillis); mCal2.setTimeInMillis(d2.mMillis); return DateUtil.inSamePeriod(mCal1, mCal2, mAggregationMs); }
public static Calendar computeNextAlarmTime( int hourOfDay, int minute, DaysOfWeek repeats, Calendar currentTime) { Calendar mustBeAfter = Calendar.getInstance(); mustBeAfter.setTimeInMillis(currentTime.getTimeInMillis()); mustBeAfter.add(Calendar.MINUTE, 1); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(currentTime.getTimeInMillis()); calendar.set(Calendar.MINUTE, minute); calendar.set(Calendar.HOUR_OF_DAY, hourOfDay); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); calendar.getTime(); // force internal recompute while (!calendar.after(mustBeAfter)) { calendar.add(Calendar.DAY_OF_WEEK, 1); // if alarm is only valid on certain days, keep incrementing till one of those days reached if (!repeats.isNoDaysSet()) { while (!repeats.isDaySet(calendar.get(Calendar.DAY_OF_WEEK))) { calendar.add(Calendar.DAY_OF_WEEK, 1); } } } return calendar; }
protected static String getCreatedText(long epoch, boolean time24hr) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(epoch); Calendar todayCal = Calendar.getInstance(); todayCal.setTimeInMillis(System.currentTimeMillis()); int hours = calendar.get(Calendar.HOUR_OF_DAY); // check if the date is from the same day if ((calendar.get(Calendar.ERA) == todayCal.get(Calendar.ERA)) && (calendar.get(Calendar.YEAR) == todayCal.get(Calendar.YEAR)) && (calendar.get(Calendar.DAY_OF_YEAR) == todayCal.get(Calendar.DAY_OF_YEAR))) { if (time24hr) { return String.format("%d:%02d", hours, calendar.get(Calendar.MINUTE)); } else { // set am/pm if (hours == 0) { return String.format("%d:%02d%s", 12, calendar.get(Calendar.MINUTE), Sonet.AM); } else if (hours < 12) { return String.format("%d:%02d%s", hours, calendar.get(Calendar.MINUTE), Sonet.AM); } else if (hours == 12) { return String.format("%d:%02d%s", hours, calendar.get(Calendar.MINUTE), Sonet.PM); } else { return String.format("%d:%02d%s", hours - 12, calendar.get(Calendar.MINUTE), Sonet.PM); } } } else { return String.format( "%s %d", Sonet.MONTHS[calendar.get(Calendar.MONTH)], calendar.get(Calendar.DATE)); } }
/** * This method is not thread safe. It has been modified from the original to not rely on global * time state. If a timestamp is in the future we return it as an absolute date string. Within the * same second we return 0s * * @param res resource * @param currentTimeMillis timestamp for offset * @param timestamp timestamp * @return the relative time string */ static String getRelativeTimeString(Resources res, long currentTimeMillis, long timestamp) { final long diff = currentTimeMillis - timestamp; if (diff >= 0) { if (diff < DateUtils.MINUTE_IN_MILLIS) { // Less than a minute ago final int secs = (int) (diff / 1000); return res.getQuantityString(R.plurals.tw__time_secs, secs, secs); } else if (diff < DateUtils.HOUR_IN_MILLIS) { // Less than an hour ago final int mins = (int) (diff / DateUtils.MINUTE_IN_MILLIS); return res.getQuantityString(R.plurals.tw__time_mins, mins, mins); } else if (diff < DateUtils.DAY_IN_MILLIS) { // Less than a day ago final int hours = (int) (diff / DateUtils.HOUR_IN_MILLIS); return res.getQuantityString(R.plurals.tw__time_hours, hours, hours); } else { final Calendar now = Calendar.getInstance(); now.setTimeInMillis(currentTimeMillis); final Calendar c = Calendar.getInstance(); c.setTimeInMillis(timestamp); final Date d = new Date(timestamp); if (now.get(Calendar.YEAR) == c.get(Calendar.YEAR)) { // Same year RELATIVE_DATE_FORMAT.applyPattern(res.getString(R.string.tw__relative_date_format_short)); } else { // Outside of our year RELATIVE_DATE_FORMAT.applyPattern(res.getString(R.string.tw__relative_date_format_long)); } return RELATIVE_DATE_FORMAT.format(d); } } RELATIVE_DATE_FORMAT.applyPattern(res.getString(R.string.tw__relative_date_format_long)); return RELATIVE_DATE_FORMAT.format(new Date(timestamp)); }
/** * True if the time is this year. * * @param time the time */ private static boolean isThisYear(long time) { Calendar now = Calendar.getInstance(); Calendar calendar = Calendar.getInstance(); now.setTimeInMillis(System.currentTimeMillis()); calendar.setTimeInMillis(time); return now.get(Calendar.YEAR) == calendar.get(Calendar.YEAR); }
private static Date[] parseTimeDuration(final String[] period) throws ParseException { Date[] range = null; if (period.length == 2 || period.length == 3) { Date begin = null; Date end = null; // Check first to see if we have any duration value within TIME parameter if (period[0].toUpperCase().startsWith("P") || period[1].toUpperCase().startsWith("P")) { long durationOffset = Long.MIN_VALUE; // Attempt to parse a time or duration from the first portion of the if (period[0].toUpperCase().startsWith("P")) { durationOffset = parsePeriod(period[0]); } else { begin = beginning(getFuzzyDate(period[0])); } if (period[1].toUpperCase().startsWith("P") && !period[1].toUpperCase().startsWith("PRESENT")) { // Invalid time period of the format: // DURATION/DURATION[/PERIOD] if (durationOffset != Long.MIN_VALUE) { throw new ParseException( "Invalid time period containing duration with no paired time value: " + Arrays.toString(period), 0); } // Time period of the format: // DURATION/TIME[/PERIOD] else { durationOffset = parsePeriod(period[1]); final Calendar calendar = new GregorianCalendar(); calendar.setTimeInMillis(begin.getTime() + durationOffset); end = calendar.getTime(); } } // Time period of the format: // TIME/DURATION[/PERIOD] else { end = end(getFuzzyDate(period[1])); final Calendar calendar = new GregorianCalendar(); calendar.setTimeInMillis(end.getTime() - durationOffset); begin = calendar.getTime(); } } // Time period of the format: // TIME/TIME[/PERIOD] else { begin = beginning(getFuzzyDate(period[0])); end = end(getFuzzyDate(period[1])); } range = new Date[2]; range[0] = begin; range[1] = end; } return range; }
public boolean isCustomHoliday(Calendar date) { if (isHolidayWorking) { SharedPreferences handle = getApplicationContext().getSharedPreferences("CUSTOM_HOLIDAYS", 0); long startL = handle.getLong("START_DATE", 0); long endL = handle.getLong("END_DATE", 0); if (startL > 0 && endL > 0) { Calendar calStart = Calendar.getInstance(); Calendar calEnd = Calendar.getInstance(); calStart.setTimeInMillis(startL); calEnd.setTimeInMillis(endL); int n = (int) ((calEnd.getTime().getTime() - calStart.getTime().getTime()) / (1000 * 60 * 60 * 24)); for (int i = 0; i <= n; i++) { if (date.compareTo(calStart) == 0) { Log.i("Holiday", date.getTime().toString()); return true; } else { calStart.add(Calendar.DATE, 1); } } } } return false; }
/** * Parse a shows airtime ms value to an actual time. If given a TVDb day string the day will get * determined, too, all respecting user settings like time zone and time offset. */ public static String[] parseMillisecondsToTime( long milliseconds, String dayofweek, Context context) { // return empty strings if time is missing if (context == null || milliseconds == -1) { return new String[] {"", ""}; } // set calendar time and day on always PST calendar // this is a workaround so we can convert the air day to a another time // zone without actually having a date final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(TIMEZONE_ALWAYS_PST)); final int year = cal.get(Calendar.YEAR); final int month = cal.get(Calendar.MONTH); final int day = cal.get(Calendar.DAY_OF_MONTH); cal.setTimeInMillis(milliseconds); // set the date back to today cal.set(year, month, day); // determine the shows common air day (Mo through Sun or daily) int dayIndex = -1; if (dayofweek != null) { dayIndex = getDayOfWeek(dayofweek); if (dayIndex > 0) { int today = cal.get(Calendar.DAY_OF_WEEK); // make sure we always assume a day which is today or later if (dayIndex - today < 0) { // we have a day before today cal.add(Calendar.DAY_OF_WEEK, (7 - today) + dayIndex); } else { // we have today or in the future cal.set(Calendar.DAY_OF_WEEK, dayIndex); } } } // convert time to local, including the day final Calendar localCal = Calendar.getInstance(); localCal.setTimeInMillis(cal.getTimeInMillis()); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); setOffsets(prefs, localCal, milliseconds); // create time string final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(context); final SimpleDateFormat dayFormat = new SimpleDateFormat("E"); final Date date = localCal.getTime(); timeFormat.setTimeZone(TimeZone.getDefault()); dayFormat.setTimeZone(TimeZone.getDefault()); String daystring = ""; if (dayIndex == 0) { daystring = context.getString(R.string.daily); } else if (dayIndex != -1) { daystring = dayFormat.format(date); } return new String[] {timeFormat.format(date), daystring}; }
/** * This method generated a URL that retrieves the requested data from the /multidata interface of * a GSN server. */ private String buildGsnDataSourceUrl( VizzlySignal signal, Long timeFilterStart, Long timeFilterEnd, int windowLengthSec, int rowLimit, Boolean includeLocation) { windowLengthSec = 1; StringBuilder urlStringBuilder = new StringBuilder(); urlStringBuilder .append("http://") .append(signal.dataSource.serverAddress) .append("/multidata?"); urlStringBuilder.append("vs[0]=").append(signal.dataSource.name); urlStringBuilder.append("&field[0]=").append(signal.dataField); // Location information if (includeLocation) { urlStringBuilder.append("&vs[1]=").append(signal.dataSource.name); urlStringBuilder.append("&field[1]=").append(signal.locationLatField); urlStringBuilder.append("&vs[2]=").append(signal.dataSource.name); urlStringBuilder.append("&field[2]=").append(signal.locationLngField); } SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy+HH:mm:ss"); Calendar cal = Calendar.getInstance(); if (timeFilterStart != null) { cal.setTimeInMillis(timeFilterStart.longValue()); urlStringBuilder.append("&from=").append(dateFormatter.format(cal.getTime())); } if (timeFilterEnd != null) { cal.setTimeInMillis(timeFilterEnd.longValue()); urlStringBuilder.append("&to=").append(dateFormatter.format(cal.getTime())); } // There are also virtual sensors that require neither a device ID, nor a position if (signal.specifiesSingleDevice()) { urlStringBuilder.append("&c_join[0]=and").append("&c_vs[0]=").append(signal.dataSource.name); urlStringBuilder.append("&c_field[0]=" + signal.deviceSelect.field); urlStringBuilder.append("&c_min[0]=").append(Integer.parseInt(signal.deviceSelect.value) - 1); urlStringBuilder.append("&c_max[0]=").append(Integer.parseInt(signal.deviceSelect.value)); } if (windowLengthSec > 1) { urlStringBuilder .append("&agg_function=avg&agg_period=1&agg_unit=") .append(windowLengthSec * 1000); } if (rowLimit != -1) { urlStringBuilder.append("&nb=SPECIFIED&nb_value=").append(rowLimit); } urlStringBuilder.append("&timeline=").append(signal.timeField); return urlStringBuilder.toString(); }
private void setDate(int year, int month, int dayOfMonth) { mCurrentDate.set(year, month, dayOfMonth); if (mCurrentDate.before(mMinDate)) { mCurrentDate.setTimeInMillis(mMinDate.getTimeInMillis()); } else if (mCurrentDate.after(mMaxDate)) { mCurrentDate.setTimeInMillis(mMaxDate.getTimeInMillis()); } }
void setDate(Calendar calendar) { mCurrentDate = mTempDate; if (mCurrentDate.before(mMinDate)) { mCurrentDate.setTimeInMillis(mMinDate.getTimeInMillis()); } else if (mCurrentDate.after(mMaxDate)) { mCurrentDate.setTimeInMillis(mMaxDate.getTimeInMillis()); } }
private String setTime(TimeTable data) { // TODO Auto-generated method stub Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Asia/Tokyo")); cal.setTimeInMillis(data.getStartDate()); String startTime = getTime(cal); cal.setTimeInMillis(data.getEndDate()); String endTime = getTime(cal); return startTime + "~" + endTime; }
/** * Converts the type of a value to comply with {@link * org.apache.calcite.rex.RexLiteral#valueMatchesType}. */ private static Object clean(Object o, RelDataType type) { if (o == null) { return null; } final Calendar calendar; switch (type.getSqlTypeName()) { case TINYINT: case SMALLINT: case INTEGER: case BIGINT: case DECIMAL: case INTERVAL_YEAR_MONTH: case INTERVAL_DAY_TIME: if (o instanceof BigDecimal) { return o; } return new BigDecimal(((Number) o).longValue()); case FLOAT: case REAL: case DOUBLE: if (o instanceof BigDecimal) { return o; } return new BigDecimal(((Number) o).doubleValue()); case CHAR: case VARCHAR: if (o instanceof NlsString) { return o; } return new NlsString((String) o, type.getCharset().name(), type.getCollation()); case TIME: if (o instanceof Calendar) { return o; } calendar = Calendar.getInstance(DateTimeUtils.GMT_ZONE); calendar.setTimeInMillis((Integer) o); return calendar; case DATE: if (o instanceof Calendar) { return o; } calendar = Calendar.getInstance(DateTimeUtils.GMT_ZONE); calendar.setTimeInMillis(0); calendar.add(Calendar.DAY_OF_YEAR, (Integer) o); return calendar; case TIMESTAMP: if (o instanceof Calendar) { return o; } calendar = Calendar.getInstance(DateTimeUtils.GMT_ZONE); calendar.setTimeInMillis((Long) o); return calendar; default: return o; } }