Exemple #1
0
  public void calculoHoras(String str_hora_inicial, String str_hora_final) {
    try {
      System.out.println("hora inicial" + str_hora_inicial);
      System.out.println("hora inicial" + str_hora_final);
      Date hora_inicial = utilitario.getHora(utilitario.getFormatoHora(str_hora_inicial));
      Date hora_final = utilitario.getHora(utilitario.getFormatoHora(str_hora_final));
      int total_segundos_hora_inicial =
          (hora_inicial.getHours() * 3600)
              + (hora_inicial.getMinutes() * 60)
              + hora_inicial.getSeconds();
      int total_segundos_hora_final =
          (hora_final.getHours() * 3600) + (hora_final.getMinutes() * 60) + hora_final.getSeconds();

      int total_diferencia_segundo = total_segundos_hora_final - total_segundos_hora_inicial;

      int total_horas = total_diferencia_segundo / 3600;
      int nuevo_valor = total_diferencia_segundo - (total_horas * 3600);
      int total_minutos = nuevo_valor / 60;
      int total_segundos = nuevo_valor - (total_minutos * 60);

      double total_diferencia_segundos =
          ((total_horas * 3600) + (total_minutos * 60) + total_segundos);
      double total_diferencia_horas = total_diferencia_segundos / 3600;

      tab_permisos.setValor(
          tab_permisos.getFilaActual(), "NRO_HORAS_ASPVH", total_diferencia_horas + "");
      utilitario.addUpdateTabla(tab_permisos, "NRO_HORAS_ASPVH", total_diferencia_horas + "");
    } catch (Exception e) {
      // TODO: handle exception
      tab_permisos.setValor(tab_permisos.getFilaActual(), "NRO_HORAS_ASPVH", "");
      utilitario.addUpdateTabla(tab_permisos, "NRO_HORAS_ASPVH", "");
    }
  }
 /**
  * 获取更新的时间
  *
  * @param date
  * @return
  */
 public static String getCreateString_PG(Date date) {
   Calendar calendar = Calendar.getInstance();
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   if (calendar.get(Calendar.YEAR) - (date.getYear() + 1900) > 0) {
     return sdf.format(date);
   } else if (calendar.get(Calendar.MONTH) - date.getMonth() > 0
       && calendar.get(Calendar.MONTH) - date.getMonth() < 12) {
     int i = calendar.get(Calendar.MONTH) - date.getDate();
     return i + "个月前";
   } else if ((calendar.get(Calendar.DAY_OF_MONTH) - date.getDate() > 0)
       && (calendar.get(Calendar.DAY_OF_MONTH) - date.getDate() < 30)) {
     int i = calendar.get(Calendar.DAY_OF_MONTH) - date.getDate();
     return i + "天前";
   } else if (calendar.get(Calendar.HOUR_OF_DAY) - date.getHours() > 0) {
     int i = calendar.get(Calendar.HOUR_OF_DAY) - date.getHours();
     return i + "小时前";
   } else if (calendar.get(Calendar.MINUTE) - date.getMinutes() > 0) {
     int i = calendar.get(Calendar.MINUTE) - date.getMinutes();
     return i + "分钟前";
   } else if (calendar.get(Calendar.SECOND) - date.getSeconds() > 0) {
     int i = calendar.get(Calendar.SECOND) - date.getSeconds();
     return i + "秒前";
   } else if (calendar.get(Calendar.SECOND) - date.getSeconds() == 0) {
     return "刚刚";
   } else {
     return sdf.format(date);
   }
 }
  @SuppressWarnings("deprecation")
  private void createAverages(Date start) {
    if (start.getMinutes() != 30 || start.getSeconds() != 0) {
      // we want to obtain estimates for full hours, i.e. 4:00 or 5:00
      // by calculating averages for 3:30-4:29:59 and 4:30-5:29:59
      throw new RuntimeException("Must start with hh:30:00");
    }

    final int HOURS = 25; // we want to have vehicles for full 24 hours, e.g. 4am to 4am next day

    long startTime = start.getTime() / 1000; // in seconds
    long endTime = startTime + HOURS * 3600; // in seconds

    taxisOverTimeHourlyAverage = new double[HOURS];
    int sum = 0;
    int hour = 0;
    int n = 0;

    for (long t = startTime; t < endTime; t++) {
      if (this.taxisOverTime.containsKey(new Date(t * 1000))) {
        sum += this.taxisOverTime.get(new Date(t * 1000)); // seconds -> milliseconds
        n++;
      }
      if (t % 3600 == 1799) { // t == hh:29:59
        taxisOverTimeHourlyAverage[hour] += (double) sum / n;
        sum = 0;
        hour++;
        n = 0;
      }
    }

    for (int i = 0; i < HOURS; i++) {
      System.out.println(i + " : " + taxisOverTimeHourlyAverage[i]);
    }
  }
  public static void writeToLog(String message) {
    int year = calendar.YEAR;
    int month = calendar.MONTH;
    month++;
    int day = calendar.DAY_OF_MONTH;

    String date = year + "-" + month + "-" + day;

    Date time = calendar.getTime();
    int hours = time.getHours();
    int minutes = time.getMinutes();
    int seconds = time.getSeconds();

    String timeS = hours + ":" + minutes + ":" + seconds;

    Date dateS = new Date();

    String timestamp = date + " " + timeS;
    Timestamp ts = new Timestamp(dateS.getTime());

    if (DynamicEconomy.logwriting) {
      try {
        bf.write("\n + [" + ts + "] " + message);
        bf.flush();
      } catch (Exception e) {
        logger.info("[DynamicEconomy] Exception writing to log.txt");
        e.printStackTrace();
      }
    }
  }
Exemple #5
0
 /**
  * Constructs a TimeOfDay from a <code>java.util.Date</code> using exactly the same field values
  * avoiding any time zone effects.
  *
  * <p>Each field is queried from the Date and assigned to the TimeOfDay. This is useful to ensure
  * that the field values are the same in the created TimeOfDay no matter what the time zone is.
  * For example, if the Calendar states that the time is 04:29, then the created TimeOfDay will
  * always have the time 04:29 irrespective of time zone issues.
  *
  * <p>This factory method always creates a TimeOfDay with ISO chronology.
  *
  * @param date the Date to extract fields from
  * @return the created TimeOfDay
  * @throws IllegalArgumentException if the calendar is null
  * @throws IllegalArgumentException if the date is invalid for the ISO chronology
  * @since 1.2
  */
 public static TimeOfDay fromDateFields(Date date) {
   if (date == null) {
     throw new IllegalArgumentException("The date must not be null");
   }
   return new TimeOfDay(
       date.getHours(), date.getMinutes(), date.getSeconds(), (int) (date.getTime() % 1000));
 }
Exemple #6
0
  public void run() {
    Date d1;
    int h, m, s;
    String heure;

    while (!fin) {
      try {
        System.out.println("launch thread");
        d1 = new Date();
        h = d1.getHours();
        m = d1.getMinutes();
        s = d1.getSeconds();

        for (HorlogeListener iphl : AHor) {
          iphl.tic(h, m, s);
        }

        heure = "h: " + h + " m: " + m + " s: " + s;
        System.out.println(heure);
        Hlab.setText(heure);
        Thread.sleep(1000);
      } catch (Exception e) {
      }
    }
  }
 public final void setTimeAsArray(String key, Date value) {
   JsArrayInteger jsArray = JavaScriptObject.createArray().cast();
   jsArray.set(0, value.getHours());
   jsArray.set(1, value.getMinutes());
   jsArray.set(2, value.getSeconds());
   set(key, jsArray);
 };
 public void adjustDate(Date d) {
   if (DateIntervalType.MILLENIUM.equals(type)) {
     d.setYear(d.getYear() + (int) quantity * 1000);
   }
   if (DateIntervalType.CENTURY.equals(type)) {
     d.setYear(d.getYear() + (int) quantity * 100);
   }
   if (DateIntervalType.DECADE.equals(type)) {
     d.setYear(d.getYear() + (int) quantity * 10);
   }
   if (DateIntervalType.YEAR.equals(type)) {
     d.setYear(d.getYear() + (int) quantity);
   }
   if (DateIntervalType.QUARTER.equals(type)) {
     d.setMonth(d.getMonth() + (int) quantity * 3);
   }
   if (DateIntervalType.MONTH.equals(type)) {
     d.setMonth(d.getMonth() + (int) quantity);
   }
   if (DateIntervalType.WEEK.equals(type)) {
     d.setDate(d.getDate() + (int) quantity * 7);
   }
   if (DateIntervalType.DAY.equals(type)) {
     d.setDate(d.getDate() + (int) quantity);
   }
   if (DateIntervalType.HOUR.equals(type)) {
     d.setHours(d.getHours() + (int) quantity);
   }
   if (DateIntervalType.MINUTE.equals(type)) {
     d.setMinutes(d.getMinutes() + (int) quantity);
   }
   if (DateIntervalType.SECOND.equals(type)) {
     d.setSeconds(d.getSeconds() + (int) quantity);
   }
 }
Exemple #9
0
 private String displayTime(String record) {
   if (record.equals("")) return "";
   String[] recordSplit = record.split("-");
   // Warning: pay attention to the following line!
   Date recordDate =
       new Date(
           Integer.parseInt(recordSplit[0]) - 1900,
           Integer.parseInt(recordSplit[1]) - 1,
           Integer.parseInt(recordSplit[2]),
           Integer.parseInt(recordSplit[3]),
           Integer.parseInt(recordSplit[4]));
   Date curDate = new Date(System.currentTimeMillis());
   String[] curSplit =
       DateFormat.format("yyyy-MM-dd-HH-mm-ss", curDate.getTime()).toString().split("-");
   if (recordSplit[2].equals(curSplit[2])) {
     return recordSplit[3] + ":" + recordSplit[4];
   } else {
     double recordTime = recordDate.getTime();
     double curTime = curDate.getTime();
     double delta =
         curDate.getHours() + curDate.getMinutes() / 60.0 + curDate.getSeconds() / 3600.0;
     if (curTime < recordTime) {
       return recordSplit[0] + "/" + recordSplit[1] + "/" + recordSplit[2];
     } else if ((curTime - recordTime) / (1000.0 * 60.0 * 60.0) - delta < 24) {
       return "昨天";
     } else if ((curTime - recordTime) / (1000.0 * 60.0 * 60.0) - delta < 168) {
       String[] day = {"天", "一", "二", "三", "四", "五", "六"};
       Calendar mCalendar = Calendar.getInstance();
       mCalendar.setTime(recordDate);
       return "星期" + day[mCalendar.get(Calendar.DAY_OF_WEEK) - 1];
     } else {
       return recordSplit[0] + "/" + recordSplit[1] + "/" + recordSplit[2];
     }
   }
 }
Exemple #10
0
  public static long[] runtimeInSecondsMonth(Context context, long timestamp, boolean monthend) {
    prefs = context.getSharedPreferences(PREFS, 0);
    Date d = new Date(timestamp);
    int month = d.getMonth();
    int year = d.getYear() + 1900;
    long mseconds = prefs.getLong("mseconds_" + month + "_" + year, 0);
    long seconds = mseconds / 1000;
    long secondsthismonth = 0;

    int daysthismonth = d.getDate() - 1;
    if (monthend) {
      daysthismonth = daysthismonth + 5;
    }
    secondsthismonth = daysthismonth * 24 * 60 * 60;
    int hourofday = d.getHours();
    secondsthismonth = secondsthismonth + hourofday * 60 * 60;
    int minuteofhour = d.getMinutes();
    secondsthismonth = secondsthismonth + minuteofhour * 60;
    int secondofminute = d.getSeconds();
    secondsthismonth = secondsthismonth + secondofminute;
    long[] result = new long[2];
    result[0] = seconds;
    result[1] = secondsthismonth;
    return result;
  }
Exemple #11
0
 /** set the time, the date part is ignored */
 @SuppressWarnings("deprecation")
 public void setTime(Date now) {
   if (DEBUG_SHOW_PUBLIC_CALLS && log.isDebugEnabled()) {
     log.debug("setTime: " + now);
   }
   issueClockSet(now.getHours(), now.getMinutes(), now.getSeconds());
 }
Exemple #12
0
  @SuppressWarnings("deprecation")
  public boolean passBooking(User currentUserBooking, User nextUserInQueue) {
    try {
      final MongoDatabase mdb = MongoDBConnManager.getInstance().getConnection();
      final MongoCollection<Document> coll = mdb.getCollection(DBConstants.COLL_BOOKING);
      final Document findCr = new Document();
      findCr.put(DBConstants.BOOKING_ID, nextUserInQueue.getBookingId());
      final ArrayList<Document> lstBkngs = coll.find(findCr).into(new ArrayList<Document>());

      for (final Document document : lstBkngs) {
        java.util.Date nextUserBookingTime = document.getDate(DBConstants.BOOKED_DATE_N_TIME);
        nextUserBookingTime.setSeconds(nextUserBookingTime.getSeconds() + 1);
        currentUserBooking.setBookedDateNTime(nextUserBookingTime);
      }

      // update current user booking time
      final Document filterQuery = new Document();
      filterQuery.put(DBConstants.BOOKING_ID, currentUserBooking.getBookingId());
      final Document updateQuery = new Document();
      final Document updateSet = new Document();
      updateSet.put(DBConstants.BOOKED_DATE_N_TIME, currentUserBooking.getBookedDateNTime());
      updateQuery.put("$set", updateSet);
      coll.updateOne(filterQuery, updateQuery);
    } catch (Exception e) {
      if (e instanceof com.mongodb.MongoTimeoutException) {
        throw new ApplicationException(MessagesEnum.MONGODB_IS_DOWN.getMessage(), e);
      }
      throw new ApplicationException(MessagesEnum.PASSING_BOOKING_FAILED.getMessage(), e);
    }
    return true;
  }
  @RequestMapping("api/admin/projectAdd.do")
  public @ResponseBody Map<String, Object> projectAdd(
      ProjectDTO fileDto, @RequestParam(value = "memberList") String memberList) {

    MultipartFile uploadFile = fileDto.getUploadFile();

    if (uploadFile != null) {

      String fileName = uploadFile.getOriginalFilename();

      Date date = new Date();
      int year = date.getYear() - 100;
      int month = date.getMonth() + 1;
      int day = date.getDate();
      int hour = date.getHours();
      int minute = date.getMinutes();
      int second = date.getSeconds();
      String time = year + "" + month + "" + day + "" + hour + "" + minute + "" + second;
      int comma = fileName.lastIndexOf(".");
      String pre = fileName.substring(0, comma);
      String end = fileName.substring(comma + 1, fileName.length());
      fileName = pre + time + "." + end;

      String projectDesc = fileDto.getProjectDesc();
      fileDto.setProjectDesc(projectDesc.replaceAll("\n", "<br>"));

      try {

        File file = new File(realPath + fileName);

        uploadFile.transferTo(file);

        fileDto.setProjectImg(fileName);

        System.out.println(memberList);
        JSONParser parser = new JSONParser();
        JSONArray ja = (JSONArray) parser.parse(memberList);
        System.out.println(ja.toJSONString());
        ArrayList list = new ArrayList();
        for (int i = 0; i < ja.size(); i++) {
          JSONObject jo = (JSONObject) ja.get(i);
          System.out.println(jo.get("userNo"));
          list.add(jo.get("userNo"));
        }

        projectDao.insertProject(fileDto);
        if (list != null) {
          Map<String, Object> param = new HashMap<String, Object>();
          param.put("list", list);
          projectMemberDao.projectMemberAdd(param);
        }

      } catch (Exception e) {
        e.printStackTrace();
      } // try - catch
    } // if

    return JsonUtil.putSuccessJsonContainer(null);
  }
  public void addLocationToList(Location cur_location) {

    if (!flag) {
      old_location = cur_location;
      startLat = cur_location.getLatitude();
      startLon = cur_location.getLongitude();
      flag = true;
    } else {
      double destLat = cur_location.getLatitude();
      double destLon = cur_location.getLongitude();
      double distance = getDistance(startLat, startLon, destLat, destLon);
      double dt = (cur_location.getTime() - old_location.getTime()) / 1000;
      double current_speed = distance / dt;
      if (Double.isNaN(current_speed) || (current_speed < 0.001)) current_speed = 0.0;
      Date currentDate = new Date();
      Calendar cal = Calendar.getInstance();
      int hour = currentDate.getHours();
      int minutes = currentDate.getMinutes();
      int seconds = currentDate.getSeconds();
      int year = currentDate.getYear() + 1900;
      int month = currentDate.getMonth() + 1;
      int day = cal.get(Calendar.DAY_OF_MONTH);
      String timestamp =
          String.valueOf(year)
              + "-"
              + String.valueOf(month)
              + "-"
              + String.valueOf(day)
              + " "
              + String.valueOf(hour)
              + ":"
              + String.valueOf(minutes)
              + ":"
              + String.valueOf(seconds);
      String move_type = "?";
      String record =
          String.valueOf(destLat)
              + ","
              + String.valueOf(destLon)
              + ","
              + String.valueOf(current_speed)
              + ","
              + "\""
              + String.valueOf(timestamp)
              + "\""
              + ","
              + String.valueOf(move_type)
              + ","
              + String.valueOf(isGpsFix);
      String type = classifyInstance(record);
      record = record.replace("?", type);
      DataToSend.add(record);
      String curPos = String.valueOf(destLat) + "," + String.valueOf(destLon) + "," + type;
      sendLocationToMap(curPos);
      startLat = cur_location.getLatitude();
      startLon = cur_location.getLongitude();
      old_location = cur_location;
    }
  }
  public static Date setHourMinuteSecond(Date date, Integer hour, Integer min) {

    Calendar t = Calendar.getInstance();
    t.setTime(date);
    t.set(Calendar.HOUR, hour);
    t.set(Calendar.MINUTE, min);
    t.set(Calendar.SECOND, date.getSeconds());
    t.set(Calendar.MILLISECOND, 0);
    return t.getTime();
  }
 @SuppressWarnings("deprecation")
 public Object transform(Object o) {
   if (o instanceof TestDate) {
     TestDate td = (TestDate) o;
     return new java.util.Date(td.year, td.month, td.date, td.hour, td.minute, td.second);
   } else if (o instanceof java.util.Date) {
     Date d = (Date) o;
     return new TestDate(
         d.getYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds());
   } else return o;
 }
 private void mergeDates(Task remote, Task local) {
   if (remote.hasDueDate() && local.hasDueTime()) {
     Date newDate = new Date(remote.getValue(Task.DUE_DATE));
     Date oldDate = new Date(local.getValue(Task.DUE_DATE));
     newDate.setHours(oldDate.getHours());
     newDate.setMinutes(oldDate.getMinutes());
     newDate.setSeconds(oldDate.getSeconds());
     long setDate = Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, newDate.getTime());
     remote.setValue(Task.DUE_DATE, setDate);
   }
 }
Exemple #18
0
  /** set Nce clock and start clock */
  @SuppressWarnings("deprecation")
  public void startHardwareClock(Date now) {
    if (DEBUG_SHOW_PUBLIC_CALLS && log.isDebugEnabled()) {
      log.debug("startHardwareClock: " + now);
    }
    if (!internalClock.getInternalMaster()
        && internalClock.getMasterName().equals(getHardwareClockName())) {}

    issueClockSet(now.getHours(), now.getMinutes(), now.getSeconds());
    issueClockStart();
  }
Exemple #19
0
 @SuppressWarnings({"deprecation", "unused"})
 private double getIntTime() {
   Date now = internalClock.getTime();
   int ms = (int) (now.getTime() % 1000);
   int ss = now.getSeconds();
   int mm = now.getMinutes();
   int hh = now.getHours();
   if (false && log.isDebugEnabled()) {
     log.debug("getIntTime: " + hh + ":" + mm + ":" + ss + "." + ms);
   }
   return ((hh * 60 * 60) + (mm * 60) + ss + (ms / 1000));
 }
  @SuppressWarnings("deprecation")
  public static synchronized void log(String prefix, String str) {
    if (LOGGER == null) {
      LOGGER = new FileLogger();
      log("Logger", "\r\n\r\n --- New Log ---");
    }
    Date d = new Date();
    int hr = d.getHours();
    int min = d.getMinutes();
    int sec = d.getSeconds();

    // I don't use DateFormat here because (in my experience), it's much slower
    StringBuffer sb = new StringBuffer(256);
    sb.append('[');
    sb.append(hr);
    sb.append(':');
    if (min < 10) sb.append('0');
    sb.append(min);
    sb.append(':');
    if (sec < 10) {
      sb.append('0');
    }
    sb.append(sec);
    sb.append("] ");
    if (prefix != null) {
      sb.append(prefix);
      sb.append("| ");
    }
    sb.append(str);
    sb.append("\r\n");
    String s = sb.toString();

    if (sLogWriter != null) {
      try {
        sLogWriter.write(s);
        sLogWriter.flush();
      } catch (IOException e) {
        // Something might have happened to the sdcard
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
          // If the card is mounted and we can create the writer, retry
          LOGGER = new FileLogger();
          if (sLogWriter != null) {
            try {
              log("FileLogger", "Exception writing log; recreating...");
              log(prefix, str);
            } catch (Exception e1) {
              // Nothing to do at this point
            }
          }
        }
      }
    }
  }
 /**
  * Returns a string representing date
  *
  * @return
  */
 public String saveDateToString() {
   String ret =
       String.format(
           "%d+%d+%d+%d+%d+%d",
           dateAdded.getDate(),
           dateAdded.getHours(),
           dateAdded.getMinutes(),
           dateAdded.getMonth(),
           dateAdded.getSeconds(),
           dateAdded.getYear());
   return ret;
 }
  @SuppressWarnings("deprecation")
  public static void LogConsole(String type, String info) {
    // Player may be null
    // determine if the log is enabled...
    if (LogIsEnabled) {

      /*
       * File BDir = new File(LogLocation); BDir.mkdir(); File TDir = new
       * File(TLogLocation+type); TDir.mkdir();
       */

      Date date = new Date();

      String LogNameFormatter = LogNameFormat;
      LogNameFormatter = LogNameFormatter.replace("{MONTH}", (date.getMonth() + 1) + "");
      LogNameFormatter = LogNameFormatter.replace("{YEAR}", (date.getYear() + 1900) + "");
      LogNameFormatter = LogNameFormatter.replace("{DAY}", date.getDate() + "");
      LogNameFormatter = LogNameFormatter.replace("{HOUR}", date.getHours() + "");
      LogNameFormatter = LogNameFormatter.replace("{DTYPE}", type);

      // File Log = new
      // File(TLogLocation+esplitter+type+"/"+LogNameFormatter);

      String LogStringFormatter = LogStringFormat;
      LogStringFormatter = LogStringFormatter.replace("{MONTH}", (date.getMonth() + 1) + "");
      LogStringFormatter = LogStringFormatter.replace("{YEAR}", (date.getYear() + 1900) + "");
      LogStringFormatter = LogStringFormatter.replace("{DAY}", date.getDate() + "");
      LogStringFormatter = LogStringFormatter.replace("{HOUR}", date.getHours() + "");
      LogStringFormatter = LogStringFormatter.replace("{MINUTE}", date.getMinutes() + "");
      LogStringFormatter = LogStringFormatter.replace("{SECOND}", date.getSeconds() + "");
      LogStringFormatter = LogStringFormatter.replace("{INFO}", info);

      // tekkitrestrict.log.info(LogStringFormatter);
      final String ttype = type;
      final String formattedName = LogNameFormatter;
      final String formatted = LogStringFormatter;
      final String TLogLocation = "log/";
      tekkitrestrict.basfo.execute(
          new Runnable() {

            @Override
            public void run() {
              LogQueue1.add(
                  new String[] {
                    ttype,
                    TLogLocation + ttype,
                    TLogLocation + ttype + "/" + formattedName,
                    formatted + "\n"
                  });
            }
          });
    }
  }
Exemple #23
0
 public static String jdbcDateFormat(java.util.Date date) {
   return (date.getYear() + 1900)
       + "-"
       + COM.dragonflow.Log.JdbcLogger.padWithZeros(date.getMonth() + 1, 2)
       + "-"
       + COM.dragonflow.Log.JdbcLogger.padWithZeros(date.getDate(), 2)
       + " "
       + COM.dragonflow.Log.JdbcLogger.padWithZeros(date.getHours(), 2)
       + ":"
       + COM.dragonflow.Log.JdbcLogger.padWithZeros(date.getMinutes(), 2)
       + ":"
       + COM.dragonflow.Log.JdbcLogger.padWithZeros(date.getSeconds(), 2);
 }
Exemple #24
0
 /*
  * Converts Java time to DOS time.
  */
 private static long javaToDosTime(long time) {
   Date d = new Date(time);
   int year = d.getYear() + 1900;
   if (year < 1980) {
     return (1 << 21) | (1 << 16);
   }
   return (year - 1980) << 25
       | (d.getMonth() + 1) << 21
       | d.getDate() << 16
       | d.getHours() << 11
       | d.getMinutes() << 5
       | d.getSeconds() >> 1;
 }
 private static DateValue setUpStartDateAsDV(Task task, Date startDate) {
   if (task.hasDueTime())
     return new DateTimeValueImpl(
         startDate.getYear() + 1900,
         startDate.getMonth() + 1,
         startDate.getDate(),
         startDate.getHours(),
         startDate.getMinutes(),
         startDate.getSeconds());
   else
     return new DateValueImpl(
         startDate.getYear() + 1900, startDate.getMonth() + 1, startDate.getDate());
 }
Exemple #26
0
  @SuppressWarnings("deprecation")
  public static void pull() {
    InputStream is = null;
    Date newTime;
    Date lastTime = new Date();
    StockQuoteList quotesToGet = new StockQuoteList();
    EquityQuoteImporter importer = EquityQuoteImporter.getImporter("yahoo");
    //        ResultsWriter writer = new ();

    ArrayList<StockAttributeType> tags = new ArrayList<>();
    tags.add(StockAttributeType.ASK);
    tags.add(StockAttributeType.BID);
    tags.add(StockAttributeType.VOLUME);
    Quote quote;

    while (true) {
      newTime = Calendar.getInstance().getTime();
      lastTime = (newTime.getSeconds() == lastTime.getSeconds()) ? lastTime : newTime;

      joutln(
          "Second is "
              + lastTime.getSeconds()
              + " and second mod 5 is "
              + (lastTime.getSeconds() % 5)
              + " "
              + "and 0 == second mod five is "
              + (0 == (lastTime.getSeconds() % 5)));

      if (0 == (lastTime.getSeconds() % 5)) {
        try {
          for (String ticker :
              quotesToGet.getTickers()) // getTickers("stocksQuotes/testStocks.xml"))
          {
            try {
              quote = importer.getQuote(ticker, tags);
              //                            writer.writeQuote(quote);
            } catch (Exception e) {
              e.printStackTrace();
            } finally {
              try {
                if (is != null) is.close();
              } catch (IOException ioe) {
                System.out.println("unhandled exception");
              }
            }
          }
        } catch (Exception e) {
          quotesToGet.fin();
        }
      }

      try {
        Thread.sleep(300);
      } catch (Exception e) {
        joutln("Thread underwent insomnia: ");
        e.printStackTrace();
      }
    }
  }
  public void inserData(String result, String status, String mode) {

    Date dt = new Date();
    int hours = dt.getHours();
    int minutes = dt.getMinutes();
    int seconds = dt.getSeconds();

    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH) + 1;
    int day = c.get(Calendar.DAY_OF_MONTH);

    int mlen = String.valueOf(month).length();
    int dlen = String.valueOf(day).length();

    if (mlen == 1) {
      dMonth = "0" + month;
    } else {
      dMonth = String.valueOf(month);
    }

    if (dlen == 1) {
      dDay = "0" + day;
    } else {
      dDay = String.valueOf(day);
    }

    String toDate = dDay + "." + dMonth + "." + year;
    String curTime = hours + ":" + minutes + ":" + seconds;

    db.addContact(new Contact(toDate, curTime, result, status, mode));
    Toast.makeText(getActivity(), "inserted..OK", Toast.LENGTH_SHORT).show();

    List<Contact> contacts = db.getAllContacts();

    for (Contact cn : contacts) {
      String log =
          cn.getDate()
              + "--"
              + cn.getTime()
              + "--"
              + cn.getResult()
              + "--"
              + cn.getStaus()
              + "--"
              + cn.getMode()
              + "\n";
      // Writing Contacts to log

      Log.d("Name: ", log);
    }
  }
 /** Converts Java time to DOS time. */
 @SuppressWarnings("deprecation") // Use of date methods
 public static long javaToDosTime(long time) {
   Date d = new Date(time);
   int year = d.getYear() + 1900;
   if (year < 1980) {
     return (1 << 21) | (1 << 16);
   }
   return (year - 1980) << 25
       | (d.getMonth() + 1) << 21
       | d.getDate() << 16
       | d.getHours() << 11
       | d.getMinutes() << 5
       | d.getSeconds() >> 1;
 }
 // Append the time and date in ISO 8601 format
 private void appendISO8601(StringBuffer sb, long millis) {
   Date date = new Date(millis);
   sb.append(date.getYear() + 1900);
   sb.append('-');
   a2(sb, date.getMonth() + 1);
   sb.append('-');
   a2(sb, date.getDate());
   sb.append('T');
   a2(sb, date.getHours());
   sb.append(':');
   a2(sb, date.getMinutes());
   sb.append(':');
   a2(sb, date.getSeconds());
 }
  public synchronized void restart() {
    if (flag) {
      Date dateBefore = new Date();
      log.error("dateBefore: " + dateBefore.getMinutes() + ":" + dateBefore.getSeconds());
      try {
        latch.await(80, TimeUnit.SECONDS);
        latch = null;
        PushClient.sendCounter = 0;
        PushClient.callBackCompletedCounter = 0;
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      Date dateAfter = new Date();
      log.error("dateAfter: " + dateAfter.getMinutes() + ":" + dateAfter.getSeconds());
      log.error("Time-Diff:" + (dateAfter.getTime() - dateBefore.getTime()));
      if (((dateAfter.getTime() - dateBefore.getTime()) > 75000)
          && (PushClient.counterAfterBeyondLimit == 0)) {
        System.out.println("**********PushClient: restart asyClient!!!");
        log.error("**********PushClient: restart asyClient!!!");
        try {
          JmsSubscription.asyClient.shutdown();
          //					PushClient.sendCounter = 0;
          //					PushClient.callBackCompletedCounter = 0;

          JmsSubscription.asyClient = null;
          Thread.sleep(3000);
          JmsSubscription.asyClient = new DefaultHttpAsyncClient();
          JmsSubscription.asyClient.start();
          flag = false;
        } catch (Exception e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  }