public static int getDay(Date origin, Date d) {
    Calendar cal1, cal2;

    cal1 = getNormalizedCalendar(origin);
    cal2 = getNormalizedCalendar(d);
    return (int) ((cal2.getTimeInMillis() - cal1.getTimeInMillis()) / ONE_DAY);
  }
  private static void setAlarm(final Context context, final String reminder_time) {
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, DevotionReminderReceiver.class);
    PendingIntent pi =
        PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    // always cancel current (if any)
    am.cancel(pi);

    if (TextUtils.isEmpty(reminder_time)) {
      return;
    }

    int hour = Integer.parseInt(reminder_time.substring(0, 2));
    int minute = Integer.parseInt(reminder_time.substring(2, 4));
    Calendar c = GregorianCalendar.getInstance();
    c.set(Calendar.HOUR_OF_DAY, hour);
    c.set(Calendar.MINUTE, minute);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);

    if (c.getTimeInMillis() < System.currentTimeMillis()) {
      c.add(Calendar.DAY_OF_YEAR, 1);
    }

    am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
  }
Exemple #3
0
  private long
      TimeDifference() { // need to check the alaram time and the triggring action time around 12

    Calendar cal = Calendar.getInstance();
    Log.d("settings.java ", " time before setting :" + cal.getTime());
    Log.d("settings.java ", " calendertime in millisec: " + cal.getTimeInMillis());
    Log.d("settings.java ", " system time in millisec :" + System.currentTimeMillis());

    // cal.setTime();

    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    // cal.set(Calendar.HOUR, 23);
    cal.set(Calendar.MINUTE, 0);
    cal.add(Calendar.DAY_OF_MONTH, 1);

    Log.d("settings.java", " time After setting day+1 and 00 hours :" + cal.getTime());

    Log.d("settings.java", " set time in millis :" + cal.getTimeInMillis());
    Log.d(
        "settings.java",
        " time of the system in millis" + Calendar.getInstance().getTimeInMillis());

    long timediff = cal.getTimeInMillis() - Calendar.getInstance().getTimeInMillis(); // +1000;

    Log.d(
        "settings.java",
        " current time: "
            + Calendar.getInstance()
            + " setted time in alaram should be 23.59.59 but is : "
            + cal.getTime()
            + "time diff in millisec :"
            + timediff);
    return timediff;
  }
  private List<Long> getPayUsers(Calendar calendar) {
    List<Long> payUserIds = new ArrayList<Long>();

    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTime(calendar.getTime());
    calendar1.set(Calendar.HOUR_OF_DAY, 0);
    calendar1.set(Calendar.MINUTE, 0);
    calendar1.set(Calendar.SECOND, 0);

    Calendar calendar2 = Calendar.getInstance();
    calendar2.setTime(calendar.getTime());
    calendar2.set(Calendar.HOUR_OF_DAY, 23);
    calendar2.set(Calendar.MINUTE, 59);
    calendar2.set(Calendar.SECOND, 59);
    try {
      PreparedStatement pstmt =
          orderCon.prepareStatement(
              "select distinct(uid) from ordersqq where time between ? and ? and cmd=7");
      pstmt.setLong(1, calendar1.getTimeInMillis());
      pstmt.setLong(2, calendar2.getTimeInMillis());
      ResultSet rs = pstmt.executeQuery();
      while (rs.next()) {
        payUserIds.add(rs.getLong(1));
      }
    } catch (Exception e) {
      logger.error("", e);
    }

    return payUserIds;
  }
Exemple #5
0
  public final int getOwnedTime() {
    if (_lastOwnedTime.getTimeInMillis() == 0) {
      return 0;
    }

    return (int) ((System.currentTimeMillis() - _lastOwnedTime.getTimeInMillis()) / 1000);
  }
  private String generateWorkingHours(final String locale) {
    Calendar calendar = Calendar.getInstance();

    calendar.set(Calendar.HOUR_OF_DAY, 8);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    long minHours = calendar.getTimeInMillis();

    calendar.set(Calendar.HOUR_OF_DAY, 20);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    long maxHours = calendar.getTimeInMillis();
    long workBeginHours = (long) (RANDOM.nextDouble() * (maxHours / 2 - minHours) + minHours);
    long workEndHours = (long) (RANDOM.nextDouble() * (maxHours - workBeginHours) + workBeginHours);

    Date workBeginDate = new Date(workBeginHours);
    Date workEndDate = new Date(workEndHours);
    StringBuilder workingHours = new StringBuilder();
    SimpleDateFormat hourFormat = new SimpleDateFormat("HH:mm", LocaleUtils.toLocale(locale));
    workingHours
        .append(hourFormat.format(workBeginDate))
        .append("-")
        .append(hourFormat.format(workEndDate));
    return workingHours.toString();
  }
  /** @see org.kuali.kfs.module.tem.document.TravelDocumentBase#initiateDocument() */
  @Override
  public void initiateDocument() {
    super.initiateDocument();

    // clear expenses
    setActualExpenses(new ArrayList<ActualExpense>());
    setPerDiemExpenses(new ArrayList<PerDiemExpense>());

    // default dates if null
    Calendar calendar = getDateTimeService().getCurrentCalendar();
    if (getTripBegin() == null) {
      calendar.add(Calendar.DAY_OF_MONTH, 1);
      setTripBegin(new Timestamp(calendar.getTimeInMillis()));
    }
    if (getTripEnd() == null) {
      calendar.add(Calendar.DAY_OF_MONTH, 2);
      setTripEnd(new Timestamp(calendar.getTimeInMillis()));
    }

    // initiate payment and wire transfer
    this.travelPayment = new TravelPayment();
    this.wireTransfer = new PaymentSourceWireTransfer();
    // set due date to the next day
    calendar = getDateTimeService().getCurrentCalendar();
    calendar.add(Calendar.DAY_OF_MONTH, 1);
    travelPayment.setDueDate(new java.sql.Date(calendar.getTimeInMillis()));
    travelPayment.setCheckStubText(
        getConfigurationService()
            .getPropertyValueAsString(TemKeyConstants.MESSAGE_TEM_REIMBURSEMENT_PAYMENT_HOLD_TEXT));

    // set up the default bank
    setDefaultBankCode();
    updatePayeeTypeForReimbursable();
  }
  public static void main(String... args) throws ParseException {
    Calendar now = Calendar.getInstance();
    System.out.println("年: " + now.get(Calendar.YEAR));
    System.out.println("月: " + (now.get(Calendar.MONTH) + 1) + "");
    System.out.println("日: " + now.get(Calendar.DAY_OF_MONTH));
    System.out.println("时: " + now.get(Calendar.HOUR_OF_DAY));
    System.out.println("分: " + now.get(Calendar.MINUTE));
    System.out.println("秒: " + now.get(Calendar.SECOND));
    System.out.println("当前时间毫秒数:" + now.getTimeInMillis());
    System.out.println(now.getTime());

    Date d = new Date();
    System.out.println(d);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dateNowStr = sdf.format(d);
    System.out.println("格式化后的日期:" + dateNowStr);

    String str = "2012-1-13 17:26:33"; // 要跟上面sdf定义的格式一样
    Date today = sdf.parse(str);
    System.out.println("字符串转成日期:" + today);

    Calendar calendar = Calendar.getInstance();
    System.out.println("year: " + calendar.get(Calendar.YEAR));
    System.out.println("month: " + calendar.get(Calendar.MONTH));
    System.out.println("day: " + calendar.get(Calendar.DAY_OF_MONTH));
    System.out.println("day of week: " + calendar.get(Calendar.DAY_OF_WEEK));

    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    int day_of_month = calendar.get(Calendar.DAY_OF_MONTH);
    int day_of_week = calendar.get(Calendar.DAY_OF_WEEK);
    calendar.set(year, month, day_of_month, 9, 30, 0);
    long amStart = calendar.getTimeInMillis();
    System.out.println(calendar.getTimeInMillis());
  }
  protected void eventActionSpecial(ActionEvent e) throws Throwable {

    if (e.getSource().equals(wbuKWZurueck)) {
      Calendar c = Calendar.getInstance();
      c.setTime(wdfKW.getDate());
      c.set(Calendar.DATE, c.get(Calendar.DATE) - 7);
      wdfKW.setTimestamp(new java.sql.Timestamp(c.getTimeInMillis()));
    } else if (e.getSource().equals(wbuNaechsteKW)) {
      Calendar c = Calendar.getInstance();
      c.setTime(wdfKW.getDate());
      c.set(Calendar.DATE, c.get(Calendar.DATE) + 7);
      wdfKW.setTimestamp(new java.sql.Timestamp(c.getTimeInMillis()));
    } else if (e.getSource().equals(wbuZeitenAbschliessen)) {
      DelegateFactory.getInstance()
          .getZeiterfassungDelegate()
          .zeitenAbschliessen(
              internalFrameZeiterfassung.getPersonalDto().getIId(), wdfKW.getTimestamp());

      DialogFactory.showModalDialog(
          LPMain.getTextRespectUISPr("lp.info"),
          LPMain.getTextRespectUISPr("pers.report.wochenabschluss.zeitenabgeschlossen")
              + wlaKW.getText());
      wbuZeitenAbschliessen.setEnabled(false);
    }
  }
  @Override
  public Reporte getReporteCliente(String identificacion, Calendar fechaInicio, Calendar fechaFin) {
    Reporte reporte = new Reporte();

    long diferenciaTicks = fechaFin.getTimeInMillis() - fechaInicio.getTimeInMillis();
    long diferenciaDias = diferenciaTicks / (1000 * 60 * 60 * 24);

    List<InformeDiario> lista = new ArrayList<>();

    for (int i = 0; i <= diferenciaDias; i++) {
      Calendar fecha = Calendar.getInstance();
      fecha.setTime(fechaInicio.getTime());
      int random1 = (int) (Math.random() * 10000);
      int random2 = (int) (Math.random() * 10000);
      fecha.add(Calendar.DAY_OF_YEAR, i);
      InformeDiario informeDiario = new InformeDiario(fecha, random1, random2, i * 1200, i * 1300);
      informeDiario.setFecha(fecha);
      lista.add(informeDiario);
    }

    reporte.setInformeDiarios(lista);

    reporte.setInformeMuebles(getReporteMuebles());

    return reporte;
  }
Exemple #11
0
  public static long TageDifferenz(String saltdatum, String sneudatum) {
    long mul1 = 0;
    long mul2 = 0;
    long mul3 = 0;

    String[] datsplit1 = saltdatum.split("\\.");
    String[] datsplit2 = sneudatum.split("\\.");
    Calendar cal1 = new GregorianCalendar();
    Calendar cal2 = new GregorianCalendar();
    cal1.set(
        Integer.parseInt(datsplit1[2]),
        Integer.parseInt(datsplit1[1]) - 1,
        Integer.parseInt(datsplit1[0]));
    cal2.set(
        Integer.parseInt(datsplit2[2]),
        Integer.parseInt(datsplit2[1]) - 1,
        Integer.parseInt(datsplit2[0]));

    mul1 = cal1.getTimeInMillis();
    mul2 = cal2.getTimeInMillis();

    mul3 = mul2 - mul1;
    if (mul3 == 0) {
      return 0;
    }
    return mul3 / (24 * 60 * 60 * 1000L);
  }
  private void parseZeoTime(JSONObject stats, String key, ZeoSleepStatsFacet facet) {
    JSONObject o = stats.getJSONObject(key);

    int day = o.getInt("day");
    int month = o.getInt("month");
    int year = o.getInt("year");
    int hours = o.getInt("hour");
    int minutes = o.getInt("minute");
    int seconds = o.getInt("second");

    Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    c.set(Calendar.MILLISECOND, 0);
    c.set(year, month - 1, day, hours, minutes, seconds);
    if (key.equals("bedTime")) {
      facet.startTimeStorage = toTimeStorage(year, month, day, hours, minutes, seconds);
      facet.start = c.getTimeInMillis();
    } else {
      facet.date =
          (new StringBuilder())
              .append(year)
              .append("-")
              .append(pad(month))
              .append("-")
              .append(pad(day))
              .toString();
      facet.endTimeStorage = toTimeStorage(year, month, day, hours, minutes, seconds);
      facet.end = c.getTimeInMillis();
    }
  }
  /** Helper method to calculate the number of days to the last payment */
  protected long getTotalDaysToLastPayment(Date lastPaymentDate, Date nextIncomeDueDate) {
    long totalDays = 0;
    long MILLISECS_PER_DAY = (1000 * 60 * 60 * 24); // total milliseconds in a day

    Calendar currentDateCalendar = Calendar.getInstance();
    currentDateCalendar.setTime(kEMService.getCurrentDate());
    currentDateCalendar.set(Calendar.HOUR, 0);
    currentDateCalendar.set(Calendar.MINUTE, 0);
    currentDateCalendar.set(Calendar.SECOND, 0);

    Calendar lastPaymentDateCalendar = Calendar.getInstance();
    lastPaymentDateCalendar.setTime(lastPaymentDate);
    lastPaymentDateCalendar.set(Calendar.HOUR, 0);
    lastPaymentDateCalendar.set(Calendar.MINUTE, 0);
    lastPaymentDateCalendar.set(Calendar.SECOND, 0);

    // to take care of leap year and day light savings time.
    long endL =
        lastPaymentDateCalendar.getTimeInMillis()
            + lastPaymentDateCalendar
                .getTimeZone()
                .getOffset(lastPaymentDateCalendar.getTimeInMillis());
    long startL =
        currentDateCalendar.getTimeInMillis()
            + currentDateCalendar.getTimeZone().getOffset(currentDateCalendar.getTimeInMillis());

    return (endL - startL) / MILLISECS_PER_DAY;
  }
Exemple #14
0
  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;
  }
Exemple #15
0
  /** Calculates the wait time between all the flights and adds it to the total travel time. */
  public void calculateWaitTime() {
    if (this.flights.size() >= 2) {
      int i = 0;
      int j = 1;
      Flight f1 = this.flights.get(i);
      Flight f2 = this.flights.get(j);
      Integer waitTime;
      boolean done = false;

      do {
        Calendar f1Arrive = f1.getArrivalDateTime();
        Calendar f2Depart = f2.getDepartureDateTime();

        // subtract departure and arrival time
        waitTime = (int) ((f2Depart.getTimeInMillis() - f1Arrive.getTimeInMillis()) / (1000 * 60));
        // Add waittime to total travel time.
        this.waitTimes.add(waitTime);
        this.totalTravelTime += waitTime;

        // end when we've calculate all waittimes
        if (j == this.flights.size() - 1) {
          done = true;
        } else {
          i++;
          j++;
          f1 = this.flights.get(i);
          f2 = this.flights.get(j);
        }
      } while (!done);
    }
  }
  @SuppressWarnings("unchecked")
  public static List<Tweet> getTweets(
      PersistenceManager pm, String user, Calendar fromDate, Calendar toDate) {
    StringBuffer jdoql = new StringBuffer("SELECT FROM ");
    jdoql.append(Tweet.class.getName());
    if (null != fromDate || null != toDate || null != user) {
      jdoql.append(" WHERE");
    }
    if (null != fromDate || null != toDate) {
      if (null != fromDate) {
        jdoql.append(" time >= ");
        jdoql.append(fromDate.getTimeInMillis());
      }
      if (null != toDate) {
        jdoql.append(" && time <= ");
        jdoql.append(toDate.getTimeInMillis());
      }
    }
    if (null == user || user.length() == 0) {
      //			jdoql.append(" && user=='schtief' ");
    } else {
      if (null != fromDate || null != toDate) jdoql.append(" && ");
      jdoql.append(" user=='");
      jdoql.append(user);
      jdoql.append("' ");
    }
    jdoql.append(" ORDER BY time ASC");

    //		String jdoql = "SELECT FROM " + Location.class.getName()+" WHERE time >=
    // "+fromDate.getTimeInMillis()+" && time <= "+toDate.getTimeInMillis()+" ORDER BY time DESC";
    List<Tweet> result = (List<Tweet>) pm.newQuery(jdoql.toString()).execute();
    System.out.println("getTweets #" + result.size() + " jdoql : " + jdoql);
    return result;
  }
Exemple #17
0
  public void fin() {

    fin = new GregorianCalendar();
    long diff = fin.getTimeInMillis() - inicio.getTimeInMillis();
    diferencia = new GregorianCalendar();
    diferencia.setTimeInMillis(diff);
  }
 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());
 }
  /**
   * Calculates the start and end time members from the given date information.
   *
   * <p>
   */
  private void calculateEntryTimes() {

    // calculate the time information for the other members
    Calendar startDay =
        new GregorianCalendar(
            m_startDate.get(Calendar.YEAR),
            m_startDate.get(Calendar.MONTH),
            m_startDate.get(Calendar.DATE));
    m_startDay = startDay.getTimeInMillis();
    m_startTime.set(Calendar.HOUR_OF_DAY, m_startDate.get(Calendar.HOUR_OF_DAY));
    m_startTime.set(Calendar.MINUTE, m_startDate.get(Calendar.MINUTE));
    m_endTime.set(Calendar.HOUR_OF_DAY, m_endDate.get(Calendar.HOUR_OF_DAY));
    m_endTime.set(Calendar.MINUTE, m_endDate.get(Calendar.MINUTE));
    m_duration = 0;
    // calculate the duration of the entry
    Calendar endDay =
        new GregorianCalendar(
            m_endDate.get(Calendar.YEAR),
            m_endDate.get(Calendar.MONTH),
            m_endDate.get(Calendar.DATE));
    if (endDay.getTimeInMillis() > startDay.getTimeInMillis()) {
      // duration at least one day, calculate it
      long delta = endDay.getTimeInMillis() - startDay.getTimeInMillis();
      m_duration = new Long(delta / MILLIS_02_PER_DAY).intValue();
    }
  }
 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());
 }
Exemple #21
0
 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() + ")");
   }
 }
Exemple #22
0
  /**
   * Devolve o fator de vencimento do boleto. Utilizado para geração do código de barras e da linha
   * digitável
   *
   * @return
   */
  public String getFatorVencimento() {
    Calendar dataBase = Calendar.getInstance();
    dataBase.set(Calendar.DAY_OF_MONTH, 7);
    dataBase.set(Calendar.MONTH, 10 - 1);
    dataBase.set(Calendar.YEAR, 1997);
    dataBase.set(Calendar.HOUR_OF_DAY, 0);
    dataBase.set(Calendar.MINUTE, 0);
    dataBase.set(Calendar.SECOND, 0);
    dataBase.set(Calendar.MILLISECOND, 0);

    Calendar vencimentoSemHoras = Calendar.getInstance();

    vencimentoSemHoras.set(
        Calendar.DAY_OF_MONTH, this.datas.getVencimento().get(Calendar.DAY_OF_MONTH));
    vencimentoSemHoras.set(Calendar.MONTH, this.datas.getVencimento().get(Calendar.MONTH));
    vencimentoSemHoras.set(Calendar.YEAR, this.datas.getVencimento().get(Calendar.YEAR));
    vencimentoSemHoras.set(Calendar.HOUR_OF_DAY, 0);
    vencimentoSemHoras.set(Calendar.MINUTE, 0);
    vencimentoSemHoras.set(Calendar.SECOND, 0);
    vencimentoSemHoras.set(Calendar.MILLISECOND, 0);

    long diferencasEmMiliSegundos =
        vencimentoSemHoras.getTimeInMillis() - dataBase.getTimeInMillis();
    long diferencasEmDias = diferencasEmMiliSegundos / (1000 * 60 * 60 * 24);

    if (diferencasEmDias > 9999) {
      throw new CriacaoBoletoException("Data fora do formato aceito!");
    }

    return String.valueOf((int) diferencasEmDias);
  }
  /**
   * @param data data para comparar com as outras duas
   * @param dataInicio
   * @param dataFim
   * @param inclusivo se true usa >= e <=, se false usa apenas > e <
   * @return true se a data for maior ou igual a inicial e menor ou igual a final, caso a dataFim
   *     e/ou a data seja(m) nulla, atrinbui a maior data possivel (31/12/9999)
   */
  public static boolean inIn(Date data, Date dataInicio, Date dataFim, boolean inclusivo) {

    if (data == null && (dataFim == null || dataInicio == null)) return true;

    // substitui as vigencias em aberto (dataFim == null)
    // jah que uma vigencia em aberto seria a maior data possivel
    if (dataFim == null) {
      Calendar calendar = new GregorianCalendar(9999, 12, 31);
      dataFim = new java.sql.Date(calendar.getTimeInMillis());
    }

    if (data == null) {
      Calendar calendar = new GregorianCalendar(9999, 12, 31);
      data = new java.sql.Date(calendar.getTimeInMillis());
    }

    if (inclusivo) {
      boolean maiorOuIgual = data.compareTo(dataInicio) >= 0;
      boolean menorOuIgual = data.compareTo(dataFim) <= 0;

      return maiorOuIgual && menorOuIgual;
    } else {
      boolean maior = data.compareTo(dataInicio) > 0;
      boolean menor = data.compareTo(dataFim) < 0;

      return maior && menor;
    }
  }
Exemple #24
0
  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 void serialize(DataOutputStream dataOut) throws IOException {
    dataOut.writeInt(idOrcamento);
    dataOut.writeInt(cliente.getIdCliente());
    dataOut.writeUTF(peso);
    dataOut.writeUTF(dimensao);
    dataOut.writeUTF(mensagem);

    long dtCadastro;
    if (dataCadastro == null) {
      dtCadastro = 0;
    } else {
      dtCadastro = dataCadastro.getTimeInMillis();
    }
    dataOut.writeLong(dtCadastro);

    long dtExclusao;
    if (dataExclusao == null) {
      dtExclusao = 0;
    } else {
      dtExclusao = dataExclusao.getTimeInMillis();
    }
    dataOut.writeLong(dtExclusao);

    dataOut.writeUTF(String.valueOf(orcamentoLido));
    dataOut.writeUTF(String.valueOf(orcamentoRespondido));
  }
  public String getTotalTime() {
    double totalTime = 0;
    String startTimeForDay = getStartTime();
    String endTimeForDay = getLastEndTimeForDay();

    if (endTimeForDay == null || startTimeForDay == null) {
      return "0";
    }
    Calendar cal = Calendar.getInstance();
    String[] endTime = endTimeForDay.split(":");
    cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(endTime[0]));
    cal.set(Calendar.MINUTE, Integer.parseInt(endTime[1]));
    long end = cal.getTimeInMillis();

    String[] startTime = startTimeForDay.split(":");
    cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(startTime[0]));
    cal.set(Calendar.MINUTE, Integer.parseInt(startTime[1]));
    long start = cal.getTimeInMillis();

    long diff = end - start;
    long hours = TimeUnit.MILLISECONDS.toHours(diff);
    long minutes = TimeUnit.MILLISECONDS.toMinutes(diff - (hours * 60 * 60 * 1000));
    double minuteD = (double) minutes / 60;

    // return DecimalFormatUtil.getFormattedData(totalTime);
    return hours + " hours" + minutes + " minutes";
  }
  @Test
  public void shouldParseAndyWarholArtistInfobox() throws MalformedURLException {

    Calendar birthDateCalendar = Calendar.getInstance();
    birthDateCalendar.set(1928, Calendar.AUGUST, 6, 0, 0, 0);
    birthDateCalendar.set(Calendar.MILLISECOND, 0);

    Calendar deathDateCalendar = Calendar.getInstance();
    deathDateCalendar.set(1987, Calendar.FEBRUARY, 22, 0, 0, 0);
    deathDateCalendar.set(Calendar.MILLISECOND, 0);

    Artist artist = WikipediaArtistInfoboxParser.parse(INFOBOX);

    Assert.assertEquals("Andy Warhol", artist.getName());
    Assert.assertEquals(
        new URL("https://en.wikipedia.org/wiki/File:Andy_Warhol_by_Jack_Mitchell.jpg"),
        artist.getImage());
    Assert.assertEquals(birthDateCalendar.getTimeInMillis(), artist.getBirthDate().getTime());
    Assert.assertEquals("Pittsburgh", artist.getBirthPlace().getName());
    Assert.assertEquals("Pennsylvania", artist.getBirthPlace().getState());
    Assert.assertEquals("United States", artist.getBirthPlace().getCountry());
    Assert.assertEquals(deathDateCalendar.getTimeInMillis(), artist.getDeathDate().getTime());
    Assert.assertEquals("New York City", artist.getDeathPlace().getName());
    Assert.assertEquals("New York", artist.getDeathPlace().getState());
    Assert.assertEquals("United States", artist.getDeathPlace().getCountry());
    Assert.assertEquals("American", artist.getNationality());
    Assert.assertEquals("Pop art", artist.getArtMovements().get(0).getName());
  }
Exemple #28
0
  /**
   * 按周获得某几周周一 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;
  }
  public static final void login(String username, MapleClient c, String pwd) {
    String login = username;
    int loginok = 0;
    boolean isBanned = c.hasBannedIP() || c.hasBannedMac() || c.hasProxyBan();
    loginok = c.login(login, pwd, isBanned);
    Calendar tempbannedTill = c.getTempBanCalendar();

    if ((loginok == 0) && (isBanned)) {
      loginok = 3;
    }
    if (loginok != 0) {
      if (!loginFailCount(c)) {
        c.clearInformation();
        c.getSession().write(LoginPacket.getLoginFailed(loginok));
      } else {
        c.getSession().close(true);
      }
    } else if (tempbannedTill.getTimeInMillis() != 0L) {
      if (!loginFailCount(c)) {
        c.clearInformation();
        c.getSession()
            .write(
                LoginPacket.getTempBan(
                    PacketHelper.getTime(tempbannedTill.getTimeInMillis()), c.getBanReason()));
      } else {
        c.getSession().close(true);
      }
    } else {
      c.loginAttempt = 0;
      LoginWorker.registerClient(c);
    }
  }
Exemple #30
0
  /**
   * Returns a string like 'Mon in 3 days', the day followed by how far it is away in relative time.
   * <br>
   * Does <b>not</b> respect user offsets or 'Use my time zone' setting. The time to be passed is
   * expected to be already corrected for that.
   */
  public static String formatToDayAndTimeWithoutOffsets(Context context, long airtime) {
    StringBuilder timeAndDay = new StringBuilder();

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(airtime);

    final SimpleDateFormat dayFormat = new SimpleDateFormat("E", Locale.getDefault());
    timeAndDay.append(dayFormat.format(cal.getTime()));

    timeAndDay.append(" ");

    // Show 'today' instead of '0 days ago'
    if (DateUtils.isToday(cal.getTimeInMillis())) {
      timeAndDay.append(context.getString(R.string.today));
    } else {
      timeAndDay.append(
          DateUtils.getRelativeTimeSpanString(
              cal.getTimeInMillis(),
              System.currentTimeMillis(),
              DateUtils.DAY_IN_MILLIS,
              DateUtils.FORMAT_ABBREV_ALL));
    }

    return timeAndDay.toString();
  }