Example usage for org.joda.time DateTime plusWeeks

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

Introduction

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

Prototype

public DateTime plusWeeks(int weeks) 

Source Link

Document

Returns a copy of this datetime plus the specified number of weeks.

Usage

From source file:cl.usach.managedbeans.TrabajoSemanalManagedBean.java

public List<Semana> buscarSemanas(Date datei, Date datef) {
    DateTime fechai = new DateTime(datei);
    DateTime fechaf = new DateTime(datef);
    LocalDate lunesI = fechai.toLocalDate().withDayOfWeek(DateTimeConstants.MONDAY);
    LocalDate domingoF = fechaf.toLocalDate().withDayOfWeek(DateTimeConstants.SUNDAY);

    List<Semana> semanas = new ArrayList<>();
    DateTime i = lunesI.toDateTimeAtStartOfDay();
    while (i.isBefore(domingoF.toDateTimeAtStartOfDay())) {
        DateTime domingoi = i.toLocalDate().withDayOfWeek(DateTimeConstants.SUNDAY).toDateTimeAtStartOfDay();
        domingoi = domingoi.plusHours(23).plusMinutes(59).plusSeconds(59);
        semanas.add(new Semana(i.toDate(), domingoi.toDate()));
        i = i.plusWeeks(1);
    }/* w  ww.j  a  v a 2 s  . co m*/
    return semanas;
}

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

License:Apache License

/**
 * getWeekList/*from   w ww .ja  v  a2s .c  om*/
 * @param day
 * @return
 */
public static List<String> getWeekList(String day) {
    List<String> weekList = new ArrayList<String>();
    DateTime datetime = DateUtil.fromDay(day);
    for (int i = 0; i < MAX_RANGE; i++) {
        weekList.add(DateUtil.toDay(datetime));
        datetime = datetime.plusWeeks(1);
    }
    return weekList;
}

From source file:com.aionemu.gameserver.network.aion.clientpackets.CM_HOUSE_PAY_RENT.java

License:Open Source License

@Override
protected void runImpl() {
    Player player = getConnection().getActivePlayer();

    if (!HousingConfig.ENABLE_HOUSE_PAY) {
        PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_MSG_F2P_CASH_HOUSE_FEE_FREE);
        return;/*from   w w w .  j  ava  2s  . co  m*/
    }

    House house = player.getActiveHouse();
    long toPay = house.getLand().getMaintenanceFee() * weekCount;
    if (toPay <= 0) {
        return;
    }
    if (player.getInventory().getKinah() < toPay) {
        PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_NOT_ENOUGH_MONEY);
        return;
    }

    long payTime = house.getNextPay() != null ? house.getNextPay().getTime()
            : (long) MaintenanceTask.getInstance().getRunTime() * 1000;
    int counter = weekCount;
    while ((--counter) >= 0) {
        payTime += MaintenanceTask.getInstance().getPeriod();
    }

    DateTime nextRun = new DateTime((long) MaintenanceTask.getInstance().getRunTime() * 1000);
    if (nextRun.plusWeeks(4).isBefore(payTime)) { //client cap
        return;
    }

    player.getInventory().decreaseKinah(toPay);
    house.setNextPay(new Timestamp(payTime));
    house.setFeePaid(true);
    house.save();
    PacketSendUtility.sendPacket(player, new SM_HOUSE_PAY_RENT(weekCount));
}

From source file:com.cisco.dvbu.ps.utils.date.DateAddDate.java

License:Open Source License

/**
 * Called to invoke the stored procedure.  Will only be called a
 * single time per instance.  Can throw CustomProcedureException or
 * SQLException if there is an error during invoke.
 *//*from   w ww  .  ja  v a 2  s  . c  om*/
@Override
public void invoke(Object[] inputValues) throws CustomProcedureException, SQLException {
    java.util.Date startDate = null;
    Calendar startCal = null;
    DateTime startDateTime = null;
    DateTime endDateTime = null;
    String datePart = null;
    int dateLength = 0;

    try {
        result = null;
        if (inputValues[0] == null || inputValues[1] == null || inputValues[2] == null) {
            return;
        }

        datePart = (String) inputValues[0];
        dateLength = (Integer) inputValues[1];

        startDate = (java.util.Date) inputValues[2];
        startCal = Calendar.getInstance();
        startCal.setTime(startDate);
        startDateTime = new DateTime(startCal.get(Calendar.YEAR), startCal.get(Calendar.MONTH) + 1,
                startCal.get(Calendar.DAY_OF_MONTH), 0, 0, 0, 0);

        if (datePart.equalsIgnoreCase("second")) {
            endDateTime = startDateTime.plusSeconds(dateLength);
        }

        if (datePart.equalsIgnoreCase("minute")) {
            endDateTime = startDateTime.plusMinutes(dateLength);
        }

        if (datePart.equalsIgnoreCase("hour")) {
            endDateTime = startDateTime.plusHours(dateLength);
        }

        if (datePart.equalsIgnoreCase("day")) {
            endDateTime = startDateTime.plusDays(dateLength);
        }

        if (datePart.equalsIgnoreCase("week")) {
            endDateTime = startDateTime.plusWeeks(dateLength);
        }

        if (datePart.equalsIgnoreCase("month")) {
            endDateTime = startDateTime.plusMonths(dateLength);
        }

        if (datePart.equalsIgnoreCase("year")) {
            endDateTime = startDateTime.plusYears(dateLength);
        }

        result = new java.sql.Date(endDateTime.getMillis());
    } catch (Throwable t) {
        throw new CustomProcedureException(t);
    }
}

From source file:com.cisco.dvbu.ps.utils.date.DateAddTimestamp.java

License:Open Source License

/**
 * Called to invoke the stored procedure.  Will only be called a
 * single time per instance.  Can throw CustomProcedureException or
 * SQLException if there is an error during invoke.
 *//* ww  w .  j a  v a  2  s . co m*/
@Override
public void invoke(Object[] inputValues) throws CustomProcedureException, SQLException {
    Timestamp startDate = null;
    Calendar startCal = null;
    DateTime startDateTime = null;
    DateTime endDateTime = null;
    String datePart = null;
    int dateLength = 0;

    try {
        result = null;
        if (inputValues[0] == null || inputValues[1] == null || inputValues[2] == null) {
            return;
        }

        datePart = (String) inputValues[0];
        dateLength = (Integer) inputValues[1];

        startDate = (Timestamp) inputValues[2];
        startCal = Calendar.getInstance();
        startCal.setTime(startDate);
        startDateTime = new DateTime(startCal.get(Calendar.YEAR), startCal.get(Calendar.MONTH) + 1,
                startCal.get(Calendar.DAY_OF_MONTH), startCal.get(Calendar.HOUR_OF_DAY),
                startCal.get(Calendar.MINUTE), startCal.get(Calendar.SECOND),
                startCal.get(Calendar.MILLISECOND));

        if (datePart.equalsIgnoreCase("second")) {
            endDateTime = startDateTime.plusSeconds(dateLength);
        }

        if (datePart.equalsIgnoreCase("minute")) {
            endDateTime = startDateTime.plusMinutes(dateLength);
        }

        if (datePart.equalsIgnoreCase("hour")) {
            endDateTime = startDateTime.plusHours(dateLength);
        }

        if (datePart.equalsIgnoreCase("day")) {
            endDateTime = startDateTime.plusDays(dateLength);
        }

        if (datePart.equalsIgnoreCase("week")) {
            endDateTime = startDateTime.plusWeeks(dateLength);
        }

        if (datePart.equalsIgnoreCase("month")) {
            endDateTime = startDateTime.plusMonths(dateLength);
        }

        if (datePart.equalsIgnoreCase("year")) {
            endDateTime = startDateTime.plusYears(dateLength);
        }

        result = new Timestamp(endDateTime.toDate().getTime());
    } catch (Throwable t) {
        throw new CustomProcedureException(t);
    }
}

From source file:com.ehdev.chronos.lib.types.holders.PayPeriodHolder.java

License:Open Source License

/**
 * Will do the calculations for the start and end of the process
 *///from   w  w  w  .ja  va2 s  . com
public void generate() {
    //Get the start and end of pay period
    DateTime startOfPP = gJob.getStartOfPayPeriod();
    gDuration = gJob.getDuration();
    DateTime endOfPP = DateTime.now(); //Today

    long duration = endOfPP.getMillis() - startOfPP.getMillis();

    DateTimeZone startZone = startOfPP.getZone();
    DateTimeZone endZone = endOfPP.getZone();

    long offset = endZone.getOffset(endOfPP) - startZone.getOffset(startOfPP);

    int weeks = (int) ((duration + offset) / 1000 / 60 / 60 / 24 / 7);

    /*
    System.out.println("end of pp: " + endOfPP);
    System.out.println("start of pp: " + startOfPP);
    System.out.println("dur: " + duration);
    System.out.println("weeks diff: " + weeks);
    */

    switch (gDuration) {
    case ONE_WEEK:
        //weeks = weeks;
        startOfPP = startOfPP.plusWeeks(weeks);
        endOfPP = startOfPP.plusWeeks(1);
        break;
    case TWO_WEEKS:
        weeks = weeks / 2;
        startOfPP = startOfPP.plusWeeks(weeks * 2);
        endOfPP = startOfPP.plusWeeks(2);
        break;
    case THREE_WEEKS:
        weeks = weeks / 3;
        startOfPP = startOfPP.plusWeeks(weeks * 3);
        endOfPP = startOfPP.plusWeeks(3);
        break;
    case FOUR_WEEKS:
        weeks = weeks / 4;
        startOfPP = startOfPP.plusWeeks(weeks * 4);
        endOfPP = startOfPP.plusWeeks(4);
        break;
    case FULL_MONTH:
        //in this case, endOfPP is equal to now
        startOfPP = DateMidnight.now().toDateTime().withDayOfMonth(1);
        endOfPP = startOfPP.plusMonths(1);

        break;
    case FIRST_FIFTEENTH:
        DateTime now = DateTime.now();
        if (now.getDayOfMonth() >= 15) {
            startOfPP = now.withDayOfMonth(15);
            endOfPP = startOfPP.plusDays(20).withDayOfMonth(1);
        } else {
            startOfPP = now.withDayOfMonth(1);
            endOfPP = now.withDayOfMonth(15);
        }
        break;
    default:
        break;
    }

    if (startOfPP.isAfter(DateTime.now())) {
        startOfPP = startOfPP.minusWeeks(getDays() / 7);
        endOfPP = endOfPP.minusWeeks(getDays() / 7);
    }

    gStartOfPP = startOfPP;
    gEndOfPP = endOfPP;
}

From source file:com.enitalk.configs.DateCache.java

public NavigableSet<DateTime> days(JsonNode tree, String tz, JsonNode teacherNode) {
    ConcurrentSkipListSet<DateTime> dates = new ConcurrentSkipListSet<>();

    Iterator<JsonNode> els = tree.elements();
    DateTimeZone dz = DateTimeZone.forID(tz);
    DateTimeFormatter hour = DateTimeFormat.forPattern("HH:mm").withZone(dz);

    DateTime today = DateTime.now().millisOfDay().setCopy(0);
    while (els.hasNext()) {

        JsonNode el = els.next();/* w w w  . ja v a2s.  c om*/
        String day = el.path("day").asText();

        boolean plus = today.getDayOfWeek() > days.get(day);
        if (el.has("start") && el.has("end")) {
            DateTime start = hour.parseDateTime(el.path("start").asText()).dayOfMonth()
                    .setCopy(today.getDayOfMonth()).monthOfYear().setCopy(today.getMonthOfYear()).year()
                    .setCopy(today.getYear()).withDayOfWeek(days.get(day)).plusWeeks(plus ? 1 : 0);
            DateTime end = hour.parseDateTime(el.path("end").asText()).dayOfMonth()
                    .setCopy(today.getDayOfMonth()).monthOfYear().setCopy(today.getMonthOfYear()).year()
                    .setCopy(today.getYear()).withDayOfWeek(days.get(day)).plusWeeks(plus ? 1 : 0);

            Hours hours = Hours.hoursBetween(start, end);
            int hh = hours.getHours() + 1;

            while (hh-- > 0) {
                dates.add(start.plusHours(hh).toDateTime(DateTimeZone.UTC));
            }
        } else {
            List<String> datesAv = jackson.convertValue(el.path("times"), List.class);
            logger.info("Array of dates {} {}", datesAv, day);

            datesAv.forEach((String dd) -> {
                DateTime date = hour.parseDateTime(dd).dayOfMonth().setCopy(today.getDayOfMonth()).monthOfYear()
                        .setCopy(today.getMonthOfYear()).year().setCopy(today.getYear())
                        .withDayOfWeek(days.get(day)).plusWeeks(plus ? 1 : 0);
                dates.add(date.toDateTime(DateTimeZone.UTC));
            });

        }

    }

    final TreeSet<DateTime> addWeek = new TreeSet<>();
    for (int i = 1; i < 2; i++) {
        for (DateTime e : dates) {
            addWeek.add(e.plusWeeks(i));

        }
    }

    dates.addAll(addWeek);

    DateTime nowUtc = DateTime.now().toDateTime(DateTimeZone.UTC);
    nowUtc = nowUtc.plusHours(teacherNode.path("notice").asInt(2));

    NavigableSet<DateTime> ss = dates.tailSet(nowUtc, true);

    return ss;

}

From source file:com.example.ashwin.popularmovies.FetchMovieTask.java

License:Apache License

protected Void doInBackground(String... params) {
    if (params.length == 0) {
        return null;
    }/*w  ww . jav  a 2 s. c  om*/
    // needs to be outside try catch to use in finally
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;

    // will contain the raw JSON response as a string
    String movieJsonStr = null;
    try {
        // http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=**REMOVED**
        Uri.Builder builder = new Uri.Builder();
        builder.scheme("http").authority("api.themoviedb.org").appendPath("3").appendPath("discover")
                .appendPath("movie");
        if (params[0].equals(mContext.getString(R.string.pref_sort_label_upcoming))) {
            // so here we need to get today's date and 3 weeks from now
            DateTime todayDt = new DateTime();
            DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
            String todayDateString = fmt.print(todayDt);
            builder.appendQueryParameter("primary_release_date.gte", todayDateString);

            // 3 weeks from now
            DateTime dtPlusTwoWeeks = todayDt.plusWeeks(3);
            String twoWeeksLaterDate = fmt.print(dtPlusTwoWeeks);
            builder.appendQueryParameter("primary_release_date.lte", twoWeeksLaterDate);
        } else {
            builder.appendQueryParameter("sort_by", params[0]);

            // here we need to get a minimum vote count, value is set to 200 minimum votes
            if (params[0].equals(mContext.getString(R.string.pref_sort_user_rating)))
                builder.appendQueryParameter("vote_count.gte", "200");
        }
        builder.appendQueryParameter("api_key", mContext.getString(R.string.tmdb_api_key));

        String website = builder.build().toString();
        URL url = new URL(website);

        // Create the request to themoviedb and open connection
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // Read the input stream into a string
        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if (inputStream == null) {
            // nothing to do
            return null;
        }
        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        while ((line = reader.readLine()) != null) {
            // doesn't affect JSON but it's a lot easier for a human to read
            buffer.append(line + "\n");
        }

        if (buffer.length() == 0) {
            // empty stream
            return null;
        }
        movieJsonStr = buffer.toString();
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error closing stream", e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                Log.e(LOG_TAG, "Error closing stream", e);
            }
        }
    }

    try {
        getMovieDataFromJsonDb(movieJsonStr);
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
    return null;
}

From source file:com.github.terma.gigaspacewebconsole.provider.executor.gigaspace.TimestampPreprocessor.java

License:Apache License

private String timestampString(Matcher matcher, final DateTime timestamp) {
    final int sign = matcher.group(1).equals("-") ? -1 : 1;
    final int quantity = sign * Integer.parseInt(matcher.group(2));
    final String type = matcher.group(3);

    DateTime updatedTimestamp;//from w w w  . j  a  v  a  2  s.c  om
    switch (type) {
    case "h":
        updatedTimestamp = timestamp.plusHours(quantity);
        break;
    case "d":
        updatedTimestamp = timestamp.plusDays(quantity);
        break;
    case "w":
        updatedTimestamp = timestamp.plusWeeks(quantity);
        break;
    default:
        throw new IllegalArgumentException();
    }

    return Long.toString(updatedTimestamp.getMillis());
}

From source file:com.goodhuddle.huddle.service.impl.PaymentServiceImpl.java

License:Open Source License

private Payment postProcessPayment(Payment payment) throws CardException, APIException, AuthenticationException,
        InvalidRequestException, APIConnectionException {

    // get the fee information
    PaymentSettings settings = getPaymentSettings();
    BalanceTransaction transaction = BalanceTransaction.retrieve(payment.getStripeBalanceTransactionId(),
            settings.getSecretKey());//from  w w  w .ja v  a2 s  . co  m
    payment.setFeesInCents(transaction.getFee());
    paymentRepository.save(payment);

    if (payment.getSubscription() != null) {
        Subscription subscription = payment.getSubscription();
        DateTime nextPaymentDue = new DateTime(payment.getPaidOn());
        switch (subscription.getFrequency()) {
        case week:
            nextPaymentDue = nextPaymentDue.plusWeeks(1);
            break;
        case month:
            nextPaymentDue = nextPaymentDue.plusMonths(1);
            break;
        case year:
            nextPaymentDue = nextPaymentDue.plusYears(1);
            break;
        default:
            throw new IllegalArgumentException("Unsupported frequency: " + subscription.getFrequency());
        }
        subscription.setNextPaymentDue(nextPaymentDue);
        subscriptionRepository.save(subscription);
    }

    return payment;
}