public static Date addMilliSeconds(Date baseDate, Long milliseconds) { Date resultDate = null; Long ms = milliseconds; if (baseDate != null && ms != null) { resultDate = new Date(baseDate.getTime() + ms); // if the dates are not in the same timezone (e.g. CET and CEST), add the difference GregorianCalendar baseDateCal = new GregorianCalendar(); baseDateCal.setTime(baseDate); int baseDateOffset = baseDateCal.get(Calendar.ZONE_OFFSET) + baseDateCal.get(Calendar.DST_OFFSET); GregorianCalendar resultDateCal = new GregorianCalendar(); resultDateCal.setTime(resultDate); int resultTimeOffset = resultDateCal.get(Calendar.ZONE_OFFSET) + resultDateCal.get(Calendar.DST_OFFSET); if (baseDateOffset != resultTimeOffset) { ms = ms - (resultTimeOffset - baseDateOffset); } resultDate = new Date(baseDate.getTime() + ms); } return resultDate; }
public static Long getDateDifferenceInMilliSeconds(Date zeroTime, Date overallTime) { Long timeDiff = null; if (overallTime != null && zeroTime != null) { timeDiff = (overallTime.getTime() - zeroTime.getTime()); // if the dates are not in the same timezone (e.g. CET and CEST), // subtract the difference GregorianCalendar zeroTimeCal = new GregorianCalendar(); zeroTimeCal.setTime(zeroTime); int zeroTimeOffset = zeroTimeCal.get(Calendar.ZONE_OFFSET) + zeroTimeCal.get(Calendar.DST_OFFSET); GregorianCalendar overallTimeCal = new GregorianCalendar(); overallTimeCal.setTime(overallTime); int overallTimeOffset = overallTimeCal.get(Calendar.ZONE_OFFSET) + overallTimeCal.get(Calendar.DST_OFFSET); if (zeroTimeOffset != overallTimeOffset) { timeDiff = timeDiff + (overallTimeOffset - zeroTimeOffset); } } return timeDiff; }
/** * Contract: get SheduleItems that ID equals to inSheduleItem.getId(); compare if the train * capacity more then current tickets count on this SheduleItem; compare if the date of departure * more then current date for 10 minutes * * @param inSheduleItem SheduleItem for which need checks * @return SheduleItem selected from database or throws exceptions * @throws NoAvailableSeatsException * @throws ExpiredTimeToBuyException */ @Transactional(readOnly = false, rollbackFor = Exception.class) public SheduleItemEntity checkTrainSeatsAndDate(SheduleItemEntity inSheduleItem) throws NoAvailableSeatsException, ExpiredTimeToBuyException { SheduleItemEntity sheduleItem = (SheduleItemEntity) this.sheduleDAO.getById(SheduleItemEntity.class, inSheduleItem.getId()); /*check available seats*/ List<SheduleItemEntity> sheduleItemsList = new ArrayList<SheduleItemEntity>(); sheduleItemsList.add(sheduleItem); sheduleItemsList = this.sheduleDAO.getBySheduleItems(sheduleItemsList); if (sheduleItem.getTrain().getCapacity() == sheduleItemsList.get(0).getTicketsList().size()) { throw new NoAvailableSeatsException(); } /*check that before departure left 10 minutes*/ GregorianCalendar currentDate = new GregorianCalendar(); currentDate.setTime(new Date()); GregorianCalendar departureDateMinus10 = new GregorianCalendar(); departureDateMinus10.setTime(sheduleItem.getDepartureDate()); departureDateMinus10.add(GregorianCalendar.MINUTE, -10); if (currentDate.after(departureDateMinus10)) { throw new ExpiredTimeToBuyException(); } return sheduleItem; }
public DiscCriteria getDisc4MemberDept(Connection connection, String code) throws SQLException { DiscCriteria result = null; String sql = " SELECT DeptID, DiscLevel, DiscRate," + " StartTime, EndTime " + " FROM discDeptMember,price_lst where price_lst.vgno=? and price_lst.deptno=CONVERT(char(15),discDeptMember.DeptID); "; PreparedStatement stmt = connection.prepareStatement(sql); stmt.setString(1, code); ResultSet rs = stmt.executeQuery(); if (rs.next()) { int deptID = rs.getInt("DeptID"); int discLevel = rs.getInt("DiscLevel"); int discRate = rs.getInt("DiscRate"); Date starttime = rs.getDate("StartTime"); Date endtime = rs.getDate("EndTime"); GregorianCalendar g_start = new GregorianCalendar(); g_start.setTime(starttime); GregorianCalendar g_end = new GregorianCalendar(); g_end.setTime(endtime); result = new Disc4MemberDept(deptID, discLevel, discRate, g_start, g_end); } return result; }
public void preencheCampos( JTextField txtDescricao, JTextField txtDataCompra, JTextField txtDataValidade, JTextField txtQuantidade, JTextField txtPrecoCompra, JTextField txtPrecoVenda, Composto composto) throws ParseException { txtDescricao.setText(composto.getDescricao()); String dia, mes, ano; GregorianCalendar calendarCompra = new GregorianCalendar(); calendarCompra.setTime(composto.getDataCompra()); dia = String.valueOf(calendarCompra.get(GregorianCalendar.DAY_OF_MONTH)); mes = String.valueOf(calendarCompra.get(GregorianCalendar.MONTH)); ano = String.valueOf(calendarCompra.get(GregorianCalendar.YEAR)); txtDataCompra.setText(dia + "/" + mes + "/" + ano); calendarCompra.setTime(composto.getDataValidade()); dia = String.valueOf(calendarCompra.get(GregorianCalendar.DAY_OF_MONTH)); mes = String.valueOf(calendarCompra.get(GregorianCalendar.MONTH)); ano = String.valueOf(calendarCompra.get(GregorianCalendar.YEAR)); txtDataValidade.setText(dia + "/" + mes + "/" + ano); txtQuantidade.setText(String.valueOf(composto.getQuantidadeEstoque())); txtPrecoCompra.setText(String.valueOf(composto.getPrecoCompra())); txtPrecoVenda.setText(String.valueOf(composto.getPrecoVenda())); }
/** * 根据商品编码从表promotion_vip里查询出商品的会员价 * * @param connection 到数据库的连接 * @param code 商品编码 * @return 普通促销信息 * @throws SQLException */ public DiscCriteria getProm4Member(Connection connection, String code) throws SQLException { DiscCriteria result = null; String sql = " SELECT vgno, promlevel, promprice, " + " startdate, enddate, starttime, endtime " + " FROM promotion_vip where vgno=?; "; PreparedStatement stmt = connection.prepareStatement(sql); stmt.setString(1, code); ResultSet rs = stmt.executeQuery(); if (rs.next()) { String vgno = Formatter.mytrim(rs.getString("vgno")); int promlevel = rs.getInt("promlevel"); double promprice = rs.getDouble("promprice"); Date startdate = rs.getDate("startdate"); Date enddate = rs.getDate("enddate"); Date starttime = rs.getDate("starttime"); Date endtime = rs.getDate("endtime"); GregorianCalendar g_start = new GregorianCalendar(); g_start.setTime(starttime); GregorianCalendar g_end = new GregorianCalendar(); g_end.setTime(endtime); result = new Prom4Member(vgno, (int) (100 * promprice), promlevel, g_start, g_end); } return result; }
/** * Parse Json Response from Alfresco REST API to create a process Definition Object. * * @param json : json response that contains data from the repository * @return ProcessDefinition Object */ @SuppressWarnings("unchecked") public static Process parseJson(Map<String, Object> json) { ProcessImpl process = new ProcessImpl(); // Public Properties process.identifier = JSONConverter.getString(json, OnPremiseConstant.ID_VALUE); String definitionIdentifier = JSONConverter.getString(json, OnPremiseConstant.DEFINITIONURL_VALUE); process.definitionIdentifier = definitionIdentifier.replace(SUFFIX_WORKFLOW_DEFINITION, ""); process.key = JSONConverter.getString(json, OnPremiseConstant.NAME_VALUE); process.name = JSONConverter.getString(json, OnPremiseConstant.TITLE_VALUE); process.priority = JSONConverter.getInteger(json, OnPremiseConstant.PRIORITY_VALUE).intValue(); process.description = JSONConverter.getString(json, OnPremiseConstant.MESSAGE_VALUE); // PARSE DATES String date = JSONConverter.getString(json, OnPremiseConstant.STARTDATE_VALUE); GregorianCalendar g = new GregorianCalendar(); SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.FORMAT_3, Locale.getDefault()); if (date != null) { g.setTime(DateUtils.parseDate(date, sdf)); process.startedAt = g; } date = JSONConverter.getString(json, OnPremiseConstant.ENDDATE_VALUE); if (date != null) { g = new GregorianCalendar(); g.setTime(DateUtils.parseDate(date, sdf)); process.endedAt = g; } // PARSE INITIATOR Map<String, Object> initiator = (Map<String, Object>) json.get(OnPremiseConstant.INITIATOR_VALUE); Person p = PersonImpl.parseJson(initiator); process.initiatorIdentifier = p.getIdentifier(); // EXTRA PROPERTIES process.data = new HashMap<String, Serializable>(); process.data.put(OnPremiseConstant.INITIATOR_VALUE, p); date = JSONConverter.getString(json, OnPremiseConstant.DUEDATE_VALUE); if (date != null) { g = new GregorianCalendar(); g.setTime(DateUtils.parseDate(date, sdf)); process.dueAt = g; } process.data.put(OnPremiseConstant.DUEDATE_VALUE, g); process.data.put( OnPremiseConstant.DESCRIPTION_VALUE, JSONConverter.getString(json, OnPremiseConstant.DESCRIPTION_VALUE)); process.data.put( OnPremiseConstant.ISACTIVE_VALUE, JSONConverter.getBoolean(json, OnPremiseConstant.ISACTIVE_VALUE)); process.hasAllVariables = true; return process; }
/** * Contract: get routes from shedule with StationInfo from filter; if in the filter exist date * then compare it with the date when train will be on the station for this route * * @param filter contains StationInfo fow which need SheduleItems info and date when train need on * the station * @return SheduleItems that satisfy to conditions */ @Transactional(readOnly = true) public List<SheduleItemEntity> searchByStation(SheduleFilter filter) { List<SheduleItemEntity> sheduleItemsList = new ArrayList<SheduleItemEntity>(); List<StationInfoEntity> stationInfoList = new ArrayList<StationInfoEntity>(); stationInfoList.add(filter.getStationInfo()); for (SheduleItemEntity sheduleItem : this.sheduleDAO.getByStations(stationInfoList)) { StationEntity station = null; for (StationEntity stationInRoute : sheduleItem.getRoute().getStationsList()) { if (stationInRoute.getStationInfo().equals(filter.getStationInfo())) { station = stationInRoute; } } if (station != null) { GregorianCalendar dateCondition = null; if (filter.getDate() != null) { dateCondition = new GregorianCalendar(); dateCondition.setTime(filter.getDate()); dateCondition = new GregorianCalendar( dateCondition.get(Calendar.YEAR), dateCondition.get(Calendar.MONTH), dateCondition.get(Calendar.DAY_OF_MONTH)); } GregorianCalendar sheduleItemDate = null; if (dateCondition != null) { sheduleItemDate = new GregorianCalendar(); sheduleItemDate.setTime(sheduleItem.getDepartureDate()); sheduleItemDate.add(Calendar.MINUTE, station.getTimeOffset()); sheduleItemDate = new GregorianCalendar( sheduleItemDate.get(Calendar.YEAR), sheduleItemDate.get(Calendar.MONTH), sheduleItemDate.get(Calendar.DAY_OF_MONTH)); } if ((dateCondition != null && sheduleItemDate != null && dateCondition.equals(sheduleItemDate)) || dateCondition == null) { try { SheduleItemEntity cloneSheduleItem = (SheduleItemEntity) sheduleItem.clone(); cloneSheduleItem.getRoute().getStationsList().clear(); cloneSheduleItem.getRoute().getStationsList().add(station); sheduleItemsList.add(cloneSheduleItem); } catch (CloneNotSupportedException exc) { exc.printStackTrace(); LOGGER.warn(exc); } } } } return sheduleItemsList; }
public View getView(Context context) throws UnsupportedOperationException { if (mType.equals("date")) { try { DateTimePicker input = new DateTimePicker(context, "yyyy-MM-dd", mValue, DateTimePicker.PickersState.DATE); input.toggleCalendar(true); mView = (View) input; } catch (UnsupportedOperationException ex) { // We can't use our custom version of the DatePicker widget because the sdk is too old. // But we can fallback on the native one. DatePicker input = new DatePicker(context); try { if (!TextUtils.isEmpty(mValue)) { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(mValue)); input.updateDate( calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); } } catch (Exception e) { Log.e(LOGTAG, "error parsing format string: " + e); } mView = (View) input; } } else if (mType.equals("week")) { DateTimePicker input = new DateTimePicker(context, "yyyy-'W'ww", mValue, DateTimePicker.PickersState.WEEK); mView = (View) input; } else if (mType.equals("time")) { TimePicker input = new TimePicker(context); input.setIs24HourView(DateFormat.is24HourFormat(context)); GregorianCalendar calendar = new GregorianCalendar(); if (!TextUtils.isEmpty(mValue)) { try { calendar.setTime(new SimpleDateFormat("HH:mm").parse(mValue)); } catch (Exception e) { } } input.setCurrentHour(calendar.get(GregorianCalendar.HOUR_OF_DAY)); input.setCurrentMinute(calendar.get(GregorianCalendar.MINUTE)); mView = (View) input; } else if (mType.equals("datetime-local") || mType.equals("datetime")) { DateTimePicker input = new DateTimePicker( context, "yyyy-MM-dd HH:mm", mValue, DateTimePicker.PickersState.DATETIME); input.toggleCalendar(true); mView = (View) input; } else if (mType.equals("month")) { DateTimePicker input = new DateTimePicker(context, "yyyy-MM", mValue, DateTimePicker.PickersState.MONTH); mView = (View) input; } return mView; }
/** * Calculates overheads for user from given backlogs( projects) * * @param from * @param weeksAhead * @param items * @return */ public HashMap<Integer, String> calculateOverheads( Date from, int weeksAhead, List<Backlog> items, User user) { GregorianCalendar cal = new GregorianCalendar(); CalendarUtils cUtils = new CalendarUtils(); HashMap<Integer, String> overheads = new HashMap<Integer, String>(); Date start = from; Date end = cUtils.nextMonday(start); cal.setTime(start); Integer week = cal.get(GregorianCalendar.WEEK_OF_YEAR); List<Assignment> assignments = new ArrayList<Assignment>(user.getAssignments()); for (int i = 1; i <= weeksAhead; i++) { // 1. Get Backlogs that hit for the week log.debug("Projects searched from :" + start); log.debug("Projects searched ending :" + end); cal.setTime(start); week = cal.get(GregorianCalendar.WEEK_OF_YEAR); log.debug("Calculating overhead for week" + week); // 2. Get projects that hit current week List<Backlog> list = this.getProjectsAndIterationsInTimeFrame(items, start, end); log.debug(list.size() + " projects found for given time frame"); // 3. Calculate overhead sum from items in those projects AFTime overhead = new AFTime(0); for (Backlog blog : list) { // Only check assignments for Projects (overhead // only set for projects not iterations) if (blog.getClass().equals(Project.class)) { Project pro = (Project) blog; for (Assignment ass : assignments) { if (ass.getBacklog().equals((Backlog) pro)) { if (pro.getDefaultOverhead() != null) { overhead.add(pro.getDefaultOverhead()); log.debug("Added overhead from project: " + pro.getDefaultOverhead()); } if (ass.getDeltaOverhead() != null) { overhead.add(ass.getDeltaOverhead()); log.debug("Added overhead from user: "******"Class was iteration class, overhead :" + blog.getClass()); } } overheads.put(week, overhead.toString()); start = cUtils.nextMonday(start); end = cUtils.nextMonday(start); cal.setTime(start); week = cal.get(GregorianCalendar.WEEK_OF_YEAR); } return overheads; }
public static boolean haveSameDate(Date d1, Date d2) { GregorianCalendar gc1 = new GregorianCalendar(); gc1.setTime(d1); GregorianCalendar gc2 = new GregorianCalendar(); gc2.setTime(d2); return ((gc1.get(Calendar.DAY_OF_MONTH) == gc2.get(Calendar.DAY_OF_MONTH)) && (gc1.get(Calendar.DAY_OF_MONTH) == gc2.get(Calendar.DAY_OF_MONTH)) && (gc1.get(Calendar.YEAR) == gc2.get(Calendar.YEAR))); }
/** @return (date1 == null) ? (date2 == null) : dayDate(date1).equals(dayDate(date2)); */ public static boolean sameDay(Date date1, Date date2) { if ((date1 != null) && (date2 != null)) { GregorianCalendar cal1 = new GregorianCalendar(); cal1.setTime(date1); GregorianCalendar cal2 = new GregorianCalendar(); cal2.setTime(date2); return fieldEqual(cal1, cal2, Calendar.YEAR) && fieldEqual(cal1, cal2, Calendar.MONTH) && fieldEqual(cal1, cal2, Calendar.DAY_OF_MONTH); } else { return date1 == date2; // they both have to be null } }
/** * Calculates the elapsed time between 2 dates. The elapsed time calculated could either be in * years, months or days * * @param type (int) The variable type determines the calculation of the elapsed time to be based * on either years, months or days. To compute the elapsed time in year input type set to * Calendar.YEAR To compute the elapsed time in month input type set to Calendar.MONTH By * default the elapsed time will compute in days * @param startDate start date * @param endDate end date * @return the elapsed time (int) */ public static int getElapsedTime(int type, Date startDate, Date endDate) { int elapsed = 0; if ((startDate == null) || (endDate == null)) { return -1; } if (startDate.after(endDate)) { return -1; } GregorianCalendar gc1 = (GregorianCalendar) GregorianCalendar.getInstance(); GregorianCalendar gc2 = (GregorianCalendar) gc1.clone(); gc1.setTime(startDate); gc2.setTime(endDate); gc1.clear(Calendar.MILLISECOND); gc1.clear(Calendar.SECOND); gc1.clear(Calendar.MINUTE); gc1.clear(Calendar.HOUR_OF_DAY); gc2.clear(Calendar.MILLISECOND); gc2.clear(Calendar.SECOND); gc2.clear(Calendar.MINUTE); gc2.clear(Calendar.HOUR_OF_DAY); if ((type != Calendar.MONTH) && (type != Calendar.YEAR)) { type = Calendar.DATE; } if (type == Calendar.MONTH) { gc1.clear(Calendar.DATE); gc2.clear(Calendar.DATE); } if (type == Calendar.YEAR) { gc1.clear(Calendar.DATE); gc2.clear(Calendar.DATE); gc1.clear(Calendar.MONTH); gc2.clear(Calendar.MONTH); } while (gc1.before(gc2)) { gc1.add(type, 1); elapsed++; } return elapsed; }
private static XMLGregorianCalendar getFechaXMLGregorianCalendar(String fecha) { Date dob = null; DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { dob = df.parse(fecha); } catch (ParseException e1) { e1.printStackTrace(); } GregorianCalendar cal = new GregorianCalendar(); cal.setTime(dob); XMLGregorianCalendar xmlDate = null; try { xmlDate = DatatypeFactory.newInstance() .newXMLGregorianCalendarDate( cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED); } catch (DatatypeConfigurationException e1) { e1.printStackTrace(); } return xmlDate; }
public long weekdays() { if (weekdays == -1) { weekdays = 0; NSTimeZone tz = NSTimeZone.timeZoneWithName("America/Los_Angeles", true); // NSTimestamp currDatePacific = new NSTimestamp(currDate.getTime(), tz); NSTimestamp startDate = new NSTimestamp(day1.getTime(), tz); GregorianCalendar cal = new GregorianCalendar(); int num = (int) calendardays(); for (int i = 0; i < num; i++) { // will check the start date, all days in-between and the end-date NSTimestamp tempDate = startDate.timestampByAddingGregorianUnits(0, 0, i, 0, 0, 0); cal.setTime(tempDate); // The day-of-week is an integer value where 1 is Sunday, 2 is Monday, ..., and 7 is // Saturday int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); if ((dayOfWeek > 1) && (dayOfWeek < 7)) { weekdays++; } } } return weekdays; }
public void execute() { // Initialize a Reminder or more than one Reminders. boolean booleanReminder = false; if (mStrReminder.compareTo(mStrReminder) == 0) booleanReminder = true; Reminder[] reminders = new Reminder[1]; if (mStrMinute.compareTo("On day of event") == 0) { Date dateReminder = getDateTime(mStrStartTime); GregorianCalendar gregorianCalendarReminder = new GregorianCalendar(); gregorianCalendarReminder.setTime(dateReminder); mStrMinute = Integer.toString( gregorianCalendarReminder.get(Calendar.HOUR_OF_DAY) * 60 + gregorianCalendarReminder.get(Calendar.MINUTE)); } reminders[0] = new Reminder(mStrMinute, mStrMethod, booleanReminder); // Initialize a Recurrence. // Initialize a Where. Where where = new Where(mStrLocation); // Initialize a When. When when = new When( getStrDateWithTimeZone(mStrStartTime), getStrDateWithTimeZone(mStrEndTime), reminders); // Initialize an Event. Event event = new Event(mStrTitle, mStrContent, where, when); // Post to Calendar for adding a new event of default calendar. Event eventNew = null; try { eventNew = mCalendarServer.postEventEntry("", event); } catch (IOException e) { Bundle bundleSend = new Bundle(); eventNew = new Event(false); bundleSend.putSerializable("Data", eventNew); bundleSend.putInt("ErrorCode", Integer.parseInt(e.getMessage())); Intent intentSend = new Intent(IntentCommand.INTENT_ACTION); intentSend.setFlags(IntentCommand.GOOGLE_CALENDAR_ADD_EVENT); intentSend.putExtras(bundleSend); mBaseService.sendBroadcast(intentSend); return; } // Get a response from Calendar, the response is a event entry, update cache. if (eventNew != null) { Bundle bundleSend = new Bundle(); bundleSend.putSerializable("Data", eventNew); Intent intentSend = new Intent(IntentCommand.INTENT_ACTION); intentSend.setFlags(IntentCommand.GOOGLE_CALENDAR_ADD_EVENT); intentSend.putExtras(bundleSend); mBaseService.sendBroadcast(intentSend); } }
public static java.util.Date proximoDiaMesAtual(java.util.Date data) { GregorianCalendar gcTmp = new GregorianCalendar(); gcTmp.setTime(data); gcTmp.add(5, 1); return gcTmp.getTime(); }
private void updateCalendarLocale(Locale l) { int oldFirstDayOfWeek = calendar.getFirstDayOfWeek(); setLocale(l); calendarComponent.setLocale(l); calendar = new GregorianCalendar(l); int newFirstDayOfWeek = calendar.getFirstDayOfWeek(); // we are showing 1 week, and the first day of the week has changed // update start and end dates so that the same week is showing if (viewMode == Mode.WEEK && oldFirstDayOfWeek != newFirstDayOfWeek) { calendar.setTime(calendarComponent.getStartDate()); calendar.add(java.util.Calendar.DAY_OF_WEEK, 2); // starting at the beginning of the week calendar.set(GregorianCalendar.DAY_OF_WEEK, newFirstDayOfWeek); Date start = calendar.getTime(); // ending at the end of the week calendar.add(GregorianCalendar.DATE, 6); Date end = calendar.getTime(); calendarComponent.setStartDate(start); calendarComponent.setEndDate(end); // Week days depend on locale so this must be refreshed setWeekendsHidden(hideWeekendsButton.getValue()); } }
private void showNotAccessedInNDays(Vector vector, Document document) { int i = getPropertyAsInteger(pNotAccessedN); if (i > 0) { Vector vector1 = new Vector(); GregorianCalendar gregoriancalendar = new GregorianCalendar(); gregoriancalendar.setTime(new Date()); gregoriancalendar.add(6, -i); Date date = gregoriancalendar.getTime(); for (int j = 0; j < vector.size(); j++) { Map map = (Map) vector.elementAt(j); Date date1 = (Date) map.get("JavaLastLogoffTime"); if (date1 == null || date1.getTime() >= date.getTime()) { continue; } Vector vector2 = new Vector(); vector1.addElement(vector2); vector2.addElement(new Pair("Mailbox", map.get("MailboxDisplayName"))); synchronized (mDisplayDateFormat) { vector2.addElement(new Pair("Last Logoff Time", mDisplayDateFormat.format(date1))); } } addListContent(vector1, "Mailboxes Not Accessed in " + i + " Days", document); } }
private Date getNextYearFor(Date date) { GregorianCalendar previousYearToDate = new GregorianCalendar(); previousYearToDate.setTime(date); int prevYear = previousYearToDate.get(Calendar.YEAR) + 1; previousYearToDate.set(Calendar.YEAR, prevYear); return previousYearToDate.getTime(); }
private Date newestDateToDelete() { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(clock.now()); calendar.add(Calendar.DAY_OF_YEAR, -settings.getRequestLogCleanupMaxAgeDays()); Date newestDateToDelete = calendar.getTime(); return newestDateToDelete; }
@RequestMapping(value = "/queryVisita", method = RequestMethod.POST) public String queryVisita(@ModelAttribute("visita") visita c, Model m, SessionStatus session) throws Exception { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); Date datum = df.parse(c.getFechaString()); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(datum); XMLGregorianCalendar xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal); /** ******************* Calling web service *********************** */ List<Visita> lista = visitaService.traeVisita(xmlCal); Iterator<Visita> i = lista.iterator(); Visita v = i.next(); visita t = new visita( datum, v.getRecomendacion(), v.getComentarios(), v.getRfc(), v.getLote(), v.getParcela(), v.getProductor(), v.getAsesor()); List<Maleza> malezas = malezaService.traeMalezas(xmlCal); Iterator<Maleza> j = malezas.iterator(); listaMalezas.clear(); while (j.hasNext()) { Maleza mal = j.next(); maleza esta = new maleza(datum, mal.getNombre(), mal.getPoblacion()); listaMalezas.add(esta); } List<Plaga> plagas = plagaService.traePlaga(xmlCal); Iterator<Plaga> k = plagas.iterator(); listaPlagas.clear(); while (k.hasNext()) { Plaga p = k.next(); maleza dieser = new maleza(datum, p.getNombre(), p.getPoblacion()); listaPlagas.add(dieser); } List<Enfermedad> sicks = enfermedadService.traeEnfermedades(xmlCal); listaSick.clear(); Iterator<Enfermedad> l = sicks.iterator(); while (l.hasNext()) { Enfermedad sick = l.next(); listaSick.add(sick.getEnfermedad()); } m.addAttribute("visitaForm", t); m.addAttribute("malezas", listaMalezas); m.addAttribute("plagas", listaPlagas); m.addAttribute("enfermedades", listaSick); return "redirect:informesDone"; }
public static IRubyObject prepareRubyDateTimeFromSqlTimestamp(Ruby runtime,Timestamp stamp){ if (stamp.getTime() == 0) { return runtime.getNil(); } gregCalendar.setTime(stamp); int month = gregCalendar.get(Calendar.MONTH); month++; // In Calendar January == 0, etc... int zoneOffset = gregCalendar.get(Calendar.ZONE_OFFSET)/3600000; RubyClass klazz = runtime.fastGetClass("DateTime"); IRubyObject rbOffset = runtime.fastGetClass("Rational") .callMethod(runtime.getCurrentContext(), "new",new IRubyObject[]{ runtime.newFixnum(zoneOffset),runtime.newFixnum(24) }); return klazz.callMethod(runtime.getCurrentContext() , "civil", new IRubyObject []{runtime.newFixnum(gregCalendar.get(Calendar.YEAR)), runtime.newFixnum(month), runtime.newFixnum(gregCalendar.get(Calendar.DAY_OF_MONTH)), runtime.newFixnum(gregCalendar.get(Calendar.HOUR_OF_DAY)), runtime.newFixnum(gregCalendar.get(Calendar.MINUTE)), runtime.newFixnum(gregCalendar.get(Calendar.SECOND)), rbOffset}); }
public StringBuilder format(Date date, StringBuilder buf) { cal.setTime(date); int year = cal.get(Calendar.YEAR); if (cal.get(Calendar.ERA) == GregorianCalendar.BC) { if (year > 1) { buf.append('-'); } year = year - 1; } pad(buf, year, 4); buf.append('-'); pad(buf, cal.get(Calendar.MONTH) + 1, 2); buf.append('-'); pad(buf, cal.get(Calendar.DAY_OF_MONTH), 2); buf.append('T'); pad(buf, cal.get(Calendar.HOUR_OF_DAY), 2); buf.append(':'); pad(buf, cal.get(Calendar.MINUTE), 2); buf.append(':'); pad(buf, cal.get(Calendar.SECOND), 2); buf.append('.'); pad(buf, cal.get(Calendar.MILLISECOND), 3); buf.append('Z'); return buf; }
private void createDateEditDialog( int year, int month, int dayOfMonth, final Date date, final boolean isStartDate) { final GregorianCalendar gc = new GregorianCalendar(); gc.setTime(date); DatePickerDialog dialog = new DatePickerDialog( this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { gc.set(Calendar.YEAR, year); gc.set(Calendar.MONTH, monthOfYear); gc.set(Calendar.DAY_OF_MONTH, dayOfMonth); if (isStartDate) { ponto.setStartDate(gc.getTime()); startDate.setText(sdfDate.format(gc.getTime())); } else { ponto.setFinishDate(gc.getTime()); finishDate.setText(sdfDate.format(gc.getTime())); } repository.saveOrUpdate(ponto); } }, year, month, dayOfMonth); dialog.show(); }
/** * 自定义时间timer 增减 月 * * @param fmtTimer * @param amount * @return */ public static Long addMonthFmtTimer(Long fmtTimer, int amount) { Date cDate = myTimerToDate(fmtTimer); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(cDate); cal.add(GregorianCalendar.MONTH, amount); return dateFmtTimer(cal.getTime()); }
/** * @param days=n n为-,则取n天前,n为+,则取n天后的日期 * @param date * @param days * @return */ public Date getSomeDaysBeforeAfter(Date date, int days) { GregorianCalendar gc = new GregorianCalendar(); gc.setTime(date); gc.add(5, days); gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc.get(Calendar.DATE)); return gc.getTime(); }
public static void loadBlocks(Chunk chunk) { ResultSet r = null; try { r = (new SQLQuery( "select l.world,l.x,l.y,l.z,b.dayPlaced,b.id from £.locations l, £.nonnatural b where l.id=b.location and l.chunkx=" + chunk.getX() + " and l.chunkz=" + chunk.getZ() + ";", msqlc)) .excecuteQuery(); } catch (MySQLSyntaxErrorException e1) { e1.printStackTrace(); } try { while (r.next()) { GregorianCalendar g = new GregorianCalendar(); g.setTime(r.getDate(5)); BlockManager.loadBlock( (new Location(Bukkit.getWorld(r.getString(1)), r.getInt(2), r.getInt(3), r.getInt(4))) .getBlock(), g, r.getInt(6)); } } catch (SQLException e) { e.printStackTrace(); } }
private static void parseFinancialDataFromXml( List<FinancialDataClass> list, int xmlResource, Resources resources) { BufferedReader reader = new BufferedReader(new InputStreamReader(resources.openRawResource(xmlResource))); try { String line = reader.readLine(); while (line != null) { String[] tokens = line.split("\t"); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(dateFormat.parse(tokens[0], new ParsePosition(0))); FinancialDataClass data = new FinancialDataClass( calendar, Float.parseFloat(tokens[1]), Float.parseFloat(tokens[2]), Float.parseFloat(tokens[3]), Float.parseFloat(tokens[4]), Float.parseFloat(tokens[5])); list.add(data); line = reader.readLine(); } reader.close(); } catch (IOException ex) { list = null; throw new Error("Could not read financial data from xml."); } }
public void updateCalendar(Date date, Date fromHour, Date toHour) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); int day = cal.get(Calendar.DAY_OF_WEEK); DayEnum dayEnum = null; if (Calendar.MONDAY == day) { dayEnum = DayEnum.MONDAY; } if (Calendar.TUESDAY == day) { dayEnum = DayEnum.TUESDAY; } if (Calendar.WEDNESDAY == day) { dayEnum = DayEnum.WEDNESDAY; } if (Calendar.THURSDAY == day) { dayEnum = DayEnum.THURSDAY; } if (Calendar.FRIDAY == day) { dayEnum = DayEnum.FRIDAY; } if (Calendar.SUNDAY == day) { dayEnum = DayEnum.SUNDAY; } if (Calendar.SATURDAY == day) { dayEnum = DayEnum.SATURDAY; } for (DayRange dayRange : calendar) { if (dayRange.getDayEnum().equals(dayEnum)) { dayRange.setRange(fromHour, toHour); dayRange.save(); } } }