Example usage for org.joda.time DateTime minusDays

List of usage examples for org.joda.time DateTime minusDays

Introduction

In this page you can find the example usage for org.joda.time DateTime minusDays.

Prototype

public DateTime minusDays(int days) 

Source Link

Document

Returns a copy of this datetime minus the specified number of days.

Usage

From source file:bamons.process.batch.task.BatchScheduledTasks.java

License:Open Source License

public void sampleJob() throws Exception {

    try {// ww  w . j  a v a2  s  . c  o m

        DateTime dt = new DateTime();
        dt = dt.minusDays(1);
        String targetDate = dt.toString(DateTimeFormat.forPattern("yyyy-MM-dd"));

        JobParameters jobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis())
                .addString("targetDate", targetDate).toJobParameters();
        JobExecution execution = jobLauncher.run(sampleJob, jobParameters);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:br.com.bob.dashboard.web.beans.HistoryBean.java

private void buildWeeks() {
    final DateTime dt = new DateTime();

    weekDates = new ArrayList<>();
    weekDates.add(utils.onlyDate(dt.toDate()));
    for (int i = 1; i < 7; i++) {
        final String result = utils.onlyDate(dt.minusDays(i).toDate());
        weekDates.add(result);// w w  w. j a va 2 s  .c  om
    }
}

From source file:ca.farrelltonsolar.classic.PVOutputUploader.java

License:Apache License

private boolean doUpload(ChargeController controller) throws InterruptedException, IOException {
    String uploadDateString = controller.uploadDate();
    String SID = controller.getSID();
    String fName = controller.getPVOutputLogFilename();
    if (fName != null && fName.length() > 0 && SID != null && SID.length() > 0) {
        DateTime logDate = PVOutputService.LogDate();
        int numberOfDays = Constants.PVOUTPUT_RECORD_LIMIT;
        if (uploadDateString.length() > 0) {
            DateTime uploadDate = DateTime.parse(uploadDateString, DateTimeFormat.forPattern("yyyy-MM-dd"));
            numberOfDays = Days.daysBetween(uploadDate, logDate).getDays();
        }/* www.j ava  2s .  co  m*/
        numberOfDays = numberOfDays > Constants.PVOUTPUT_RECORD_LIMIT ? Constants.PVOUTPUT_RECORD_LIMIT
                : numberOfDays; // limit to 20 days as per pvOutput limits
        if (numberOfDays > 0) {
            Log.d(getClass().getName(), String.format("PVOutput uploading: %s for %d days on thread: %s", fName,
                    numberOfDays, Thread.currentThread().getName()));
            DateTime now = DateTime.now();
            String UploadDate = DateTimeFormat.forPattern("yyyy-MM-dd").print(now);
            Bundle logs = load(fName);
            float[] mData = logs.getFloatArray(String.valueOf(Constants.CLASSIC_KWHOUR_DAILY_CATEGORY)); // kWh/day
            boolean uploadDateRecorded = false;
            for (int i = 0; i < numberOfDays; i++) {
                logDate = logDate.minusDays(1); // latest log entry is for yesterday
                Socket pvOutputSocket = Connect(pvOutput);
                DataOutputStream outputStream = new DataOutputStream(
                        new BufferedOutputStream(pvOutputSocket.getOutputStream()));
                String dateStamp = DateTimeFormat.forPattern("yyyyMMdd").print(logDate);
                StringBuilder feed = new StringBuilder("GET /service/r2/addoutput.jsp");
                feed.append("?key=");
                feed.append(APIKey);
                feed.append("&sid=");
                feed.append(SID);
                feed.append("&d=");
                feed.append(dateStamp);
                feed.append("&g=");
                String wh = String.valueOf(mData[i] * 100);
                feed.append(wh);
                feed.append("\r\n");
                feed.append("Host: ");
                feed.append(pvOutput);
                feed.append("\r\n");
                feed.append("\r\n");
                String resp = feed.toString();
                outputStream.writeBytes(resp);
                outputStream.flush();
                pvOutputSocket.close();
                if (uploadDateRecorded == false) {
                    controller.setUploadDate(UploadDate);
                    uploadDateRecorded = true;
                }
                Thread.sleep(Constants.PVOUTPUT_RATE_LIMIT); // rate limit
            }
            return true;
        }
    }
    return false;
}

From source file:ch.icclab.cyclops.client.UdrServiceClient.java

License:Open Source License

/**
 * Connects to the UDR Service and requests for the CDRs for a user between a time period
 *
 * @param from   String/*from w w  w .  jav a 2s.co  m*/
 * @param to     String
 * @param userId String
 * @param resourceId String
 * @return String
 */
public String getUserUsageData(String userId, String resourceId, Integer from, Integer to) {
    logger.trace(
            "BEGIN UserUsage getUserUsageData(String userId, String resourceId, Integer from, Integer to) throws IOException");
    logger.trace("DATA UserUsage getUserUsageData...: user=" + userId);
    Gson gson = new Gson();
    LinearRegressionPredict predict = new LinearRegressionPredict();
    //parse dates
    DateTime now = new DateTime(DateTimeZone.UTC);
    Long time_to = now.plusDays(to).getMillis();
    String time_string_from = now.minusDays(from).toString("yyyy-MM-dd'T'HH:mm:ss'Z'");
    ArrayList<Double> list_of_points = Time.makeListOfTIme(now, time_to, to);

    ClientResource resource = new ClientResource(url + "/usage/users/" + userId);
    resource.getReference().addQueryParameter("from", time_string_from);
    logger.trace("DATA UserUsage getUserUsageData...: url=" + resource.toString());
    resource.get(MediaType.APPLICATION_JSON);
    Representation output = resource.getResponseEntity();
    PredictionResponse result = new PredictionResponse();
    try {
        JSONObject resultArray = new JSONObject(output.getText());
        logger.trace("DATA UserUsage getUserUsageData...: output=" + resultArray.toString());
        logger.trace("DATA UserUsage getUsageUsageData...: resultArray=" + resultArray);
        String result_array = resultArray.toString();
        if (result_array.contains("OpenStack")) {
            result_array = result_array.replace("OpenStack", "External");
        }
        UdrServiceResponse usageDataRecords = gson.fromJson(result_array, UdrServiceResponse.class);
        logger.trace("DATA UserUsage getUserUsageData...: userUsageData=" + usageDataRecords);
        result = predict.predict(usageDataRecords, resourceId, list_of_points);
        // Fit "from" and "to" fields
        result.setFrom(time_string_from);
        result.setTo(Time.MillsToString(time_to.doubleValue()));
        logger.trace("DATA UserUsage getUserUsageData...: userUsageData=" + gson.toJson(result));

    } catch (JSONException e) {
        e.printStackTrace();
        logger.error("EXCEPTION JSONEXCEPTION UserUsage getUserUsageData...");
    } catch (IOException e) {
        logger.error("EXCEPTION IOEXCEPTION UserUsage getUserUsageData...");
        e.printStackTrace();
    }

    return gson.toJson(result);
}

From source file:classes.Querys.java

private String restarDias(String fecha, Integer cantidad) throws ParseException {

    DateTime dateTime = DateTime.parse(fecha, DateTimeFormat.forPattern("dd-MM-yyyy"));

    dateTime = dateTime.minusDays(cantidad);

    return dateTime.toString("dd-MM-yyyy");

}

From source file:cn.cuizuoli.appranking.util.DateUtil.java

License:Apache License

/**
 * minusDays/*from ww  w . ja  v  a  2 s . c  om*/
 * @param day
 * @param days
 * @return
 */
public static String minusDays(String day, int days) {
    DateTime datetime = fromDay(day);
    return toDay(datetime.minusDays(days));
}

From source file:com.addthis.hydra.data.util.DateUtil.java

License:Apache License

public static DateTime getDateTime(DateTimeFormatter formatter, String date) {
    if (date.startsWith(NOW_PREFIX) && date.endsWith(NOW_POSTFIX)) {
        if (date.equals(NOW)) {
            return new DateTime();
        }/*  w  w  w  . ja v  a  2  s.co  m*/
        DateTime time = new DateTime();
        int pos;
        if ((pos = date.indexOf("+")) > 0) {
            time = time
                    .plusDays(Integer.parseInt(date.substring(pos + 1, date.length() - NOW_POSTFIX.length())));
        } else if ((pos = date.indexOf("-")) > 0) {
            time = time
                    .minusDays(Integer.parseInt(date.substring(pos + 1, date.length() - NOW_POSTFIX.length())));
        }
        return time;
    }
    return formatter.parseDateTime(date);
}

From source file:com.aionemu.gameserver.model.house.MaintenanceTask.java

License:Open Source License

@Override
protected void executeTask() {
    if (!HousingConfig.ENABLE_HOUSE_PAY) {
        return;//www  . jav a2  s. co m
    }

    // Get times based on configuration values
    DateTime now = new DateTime();
    DateTime previousRun = now.minus(getPeriod()); // usually week ago
    DateTime beforePreviousRun = previousRun.minus(getPeriod()); // usually two weeks ago

    for (House house : maintainedHouses) {
        if (house.isFeePaid()) {
            continue; // player already paid, don't check
        }
        long payTime = house.getNextPay().getTime();
        long impoundTime = 0;
        int warnCount = 0;

        PlayerCommonData pcd = null;
        Player player = World.getInstance().findPlayer(house.getOwnerId());
        if (player == null) {
            pcd = DAOManager.getDAO(PlayerDAO.class).loadPlayerCommonData(house.getOwnerId());
        } else {
            pcd = player.getCommonData();
        }

        if (pcd == null) {
            // player doesn't exist already for some reasons
            log.warn("House " + house.getAddress().getId()
                    + " had player assigned but no player exists. Auctioned.");
            putHouseToAuction(house, null);
            continue;
        }

        if (payTime <= beforePreviousRun.getMillis()) {
            DateTime plusDay = beforePreviousRun.minusDays(1);
            if (payTime <= plusDay.getMillis()) {
                // player didn't pay after the second warning and one day passed
                impoundTime = now.getMillis();
                warnCount = 3;
                putHouseToAuction(house, pcd);
            } else {
                impoundTime = now.plusDays(1).getMillis();
                warnCount = 2;
            }
        } else if (payTime <= previousRun.getMillis()) {
            // player did't pay 1 period
            impoundTime = now.plus(getPeriod()).plusDays(1).getMillis();
            warnCount = 1;
        } else {
            continue; // should not happen
        }

        if (pcd.isOnline()) {
            if (warnCount == 3) {
                PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_MSG_HOUSING_SEQUESTRATE);
            } else {
                PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_MSG_HOUSING_OVERDUE);
            }
        }
        MailFormatter.sendHouseMaintenanceMail(house, warnCount, impoundTime);
    }
}

From source file:com.aionemu.gameserver.services.HousingBidService.java

License:Open Source License

public boolean isBiddingAllowed() {
    DateTime now = DateTime.now();//from   w  ww .  j  a  va  2 s  . co  m
    DateTime auctionEnd = new DateTime(((long) getRunTime() + timeProlonged * 60) * 1000);
    if (now.getDayOfWeek() == auctionEnd.getDayOfWeek() && auctionEnd.minusDays(1).isAfterNow()) {
        // Auction is unavailable from Sunday 12 PM to Monday
        return false;
    }
    return true;
}

From source file:com.aliakseipilko.flightdutytracker.presenter.impl.HourPresenter.java

License:Open Source License

@Override
public void getDutyHoursInPastDays(int days) {

    DateTime dateTime = DateTime.now();
    Date startDate = dateTime.minusDays(days).toDate();

    repository.getMultipleFlightsByDateRange(startDate, new Date(), Sort.DESCENDING,
            getMultipleFlightsDutyHoursCallback);
}