Example usage for org.joda.time DateTime toLocalDate

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

Introduction

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

Prototype

public LocalDate toLocalDate() 

Source Link

Document

Converts this object to a LocalDate with the same date and chronology.

Usage

From source file:org.openmrs.mobile.utilities.DateUtils.java

License:Open Source License

public static String calculateAge(String dateOfBirth) {
    int ageInYears;
    int ageInMonths;
    int ageInDays;
    DateTime birthDate;
    DateTime currentTime;//  www. jav a 2 s  . c  o m

    try {
        birthDate = new DateTime(SIMPLE_DATE_FORMAT.parse(dateOfBirth));
        currentTime = new DateTime();
        if (birthDate.isAfter(currentTime)) {
            OpenMRS.getInstance().getLogger().w(TAG, "Can't be born in the future");
            return ApplicationConstants.EMPTY_STRING;
        }

        ageInYears = Years.yearsBetween(birthDate.toLocalDate(), currentTime.toLocalDate()).getYears();
        ageInMonths = Months.monthsBetween(birthDate.toLocalDate(), currentTime.toLocalDate()).getMonths();
        ageInDays = Days.daysBetween(birthDate.toLocalDate(), currentTime.toLocalDate()).getDays();
    } catch (ParseException e) {
        OpenMRS.getInstance().getLogger().e(TAG, "Error parsing date: " + dateOfBirth, e);
        return ApplicationConstants.EMPTY_STRING;
    }

    if (ageInYears > 0) {
        return String.valueOf(ageInYears);
    } else if (ageInMonths == 1) {
        return ageInMonths + " month";
    } else if (ageInMonths > 1) {
        return ageInMonths + " months";
    } else if (ageInDays == 1) {
        return ageInDays + " day";
    } else
        return ageInDays + " days";
}

From source file:org.projectbuendia.client.ui.chart.LocalizedChartDataGridAdapter.java

License:Apache License

public LocalizedChartDataGridAdapter(Context context, List<LocalizedObs> observations, LocalDate admissionDate,
        LocalDate firstSymptomsDate, LayoutInflater layoutInflater) {
    mContext = context;/*from w  w w . j a  v a  2 s . co  m*/
    LocalizedChartHelper localizedChartHelper = new LocalizedChartHelper(context.getContentResolver());
    mLayoutInflater = layoutInflater;
    Resources resources = context.getResources();
    mAdmissionDate = admissionDate;
    mFirstSymptomsDate = firstSymptomsDate;

    // Even though these Drawables are currently identical, referencing different drawables
    // for row headers and table cells ensures that RecyclerView does not improperly reuse
    // one as the other.
    this.mBackgroundLight = resources.getDrawable(R.drawable.chart_grid_background_light);
    this.mBackgroundDark = resources.getDrawable(R.drawable.chart_grid_background_dark);
    this.mRowHeaderBackgroundLight = resources.getDrawable(R.drawable.chart_grid_row_header_background_light);
    this.mRowHeaderBackgroundDark = resources.getDrawable(R.drawable.chart_grid_row_header_background_dark);

    Row row = null;
    TreeSet<LocalDate> days = new TreeSet<>();
    mToday = LocalDate.now(mChronology);
    for (LocalizedObs ob : observations) {
        // Observations come through ordered by the chart row, then the observation time, so we
        // want to maintain that order.
        if (row == null || !ob.conceptName.equals(row.mName)) {
            row = new Row(ob.conceptUuid, ob.conceptName);
            mRows.add(row);
        }

        if (ob.value == null || Concepts.UNKNOWN_UUID.equals(ob.value)
                || LocalizedChartHelper.NO_SYMPTOM_VALUES.contains(ob.value)) {
            // Don't display anything in the cell if there are no positive observations.
            continue;
        }

        DateTime obsDateTime = new DateTime(ob.encounterTimeMillis, mChronology);
        String columnId = toColumnId(obsDateTime);
        days.add(obsDateTime.toLocalDate());

        LOG.v("Column: %s, Observation: %s", columnId, ob.toString());
        if (row.mColumnIdsToLocalizedValues.containsKey(columnId)) {
            LOG.v("Overriding previous observation with value: %s",
                    row.mColumnIdsToLocalizedValues.get(columnId));
        }

        // If this is any bleeding site, also show a dot in the "any bleeding" row.
        if (Concepts.BLEEDING_SITES_NAME.equals(ob.groupName)) {
            mColumnIdsWithAnyBleeding.add(columnId);
        }

        // For notes, perform a concatenation rather than overwriting.
        if (Concepts.NOTES_UUID.equals(ob.conceptUuid)) {
            String oldText = row.mColumnIdsToValues.get(columnId);
            String newText = (oldText == null ? "" : oldText + "\n\n") + Dates.toMediumString(obsDateTime)
                    + "\n" + ob.value;
            row.mColumnIdsToValues.put(columnId, newText);
        } else {
            row.mColumnIdsToValues.put(columnId, ob.value);
        }

        row.mColumnIdsToLocalizedValues.put(columnId, ob.localizedValue);
    }

    // Create the list of all the columns to show.  Today and the admission date should
    // always be present, as well as any days between the last observation and today.
    days.add(mToday);
    if (admissionDate != null) {
        days.add(admissionDate);
    }
    LocalDate lastDay = days.last();
    for (LocalDate d = days.first(); !d.isAfter(lastDay); d = d.plus(Days.ONE)) {
        DateTime dayStart = d.toDateTimeAtStartOfDay();
        mColumnIds.add(toColumnId(dayStart));
        mColumnIds.add(toColumnId(dayStart.withHourOfDay(12)));
    }

    // If there are no observations, put some known rows to make it clearer what is being
    // displayed.
    if (mRows.isEmpty()) {
        List<LocalizedObs> emptyChart = localizedChartHelper.getEmptyChart(LocalizedChartHelper.ENGLISH_LOCALE);
        for (LocalizedObs ob : emptyChart) {
            mRows.add(new Row(ob.conceptUuid, ob.conceptName));
        }
    }
}

From source file:org.projectbuendia.client.ui.chart.LocalizedChartDataGridAdapter.java

License:Apache License

private String formatColumnHeader(String columnId) {
    DateTime dateTime = DateTime.parse(columnId).withChronology(mChronology);
    LocalDate date = dateTime.toLocalDate();
    Resources res = mContext.getResources();

    int admitDay = Dates.dayNumberSince(mAdmissionDate, date);
    String admitDayLabel = (admitDay >= 1) ? res.getString(R.string.day_n, admitDay) : "";

    String dateString = date.toString("d MMM");
    String dateLabel = date.equals(mToday) ? res.getString(R.string.today_date, dateString) : dateString;

    // The column header has two lines of text: the first line gives the day number since
    // admission and the second line gives the calendar date.  Pending feedback from the field
    // on its importance, the symptom onset day number could also be shown in the column
    // header in a different colour.  This would be done by constructing HTML and using
    // Html.fromHtml() to produce a Spanned object that will be rendered by the TextView.
    return admitDayLabel + "\n" + dateLabel;
}

From source file:org.projectbuendia.client.ui.dialogs.OrderDialogFragment.java

License:Apache License

private void populateFields(Bundle args) {
    String instructions = args.getString("instructions");
    mMedication.setText(Order.getMedication(instructions));
    mDosage.setText(Order.getDosage(instructions));
    mFrequency.setText(Order.getFrequency(instructions));
    DateTime now = Utils.getDateTime(args, "now_millis");
    Long stopMillis = Utils.getLong(args, "stop_millis");
    if (stopMillis != null) {
        LocalDate lastDay = new DateTime(stopMillis).toLocalDate();
        int days = Days.daysBetween(now.toLocalDate(), lastDay).getDays();
        if (days >= 0) {
            mGiveForDays.setText("" + (days + 1)); // 1 day means stop after today
        }/*from  ww  w .j av  a2s.c om*/
    }
    updateLabels();
}

From source file:org.projectbuendia.client.ui.dialogs.OrderDialogFragment.java

License:Apache License

public void onSubmit(Dialog dialog) {
    String uuid = getArguments().getString("uuid");
    String patientUuid = getArguments().getString("patientUuid");
    String medication = mMedication.getText().toString().trim();
    String dosage = mDosage.getText().toString().trim();
    String frequency = mFrequency.getText().toString().trim();

    String instructions = Order.getInstructions(medication, dosage, frequency);
    String durationStr = mGiveForDays.getText().toString().trim();
    Integer durationDays = durationStr.isEmpty() ? null : Integer.valueOf(durationStr);
    boolean valid = true;
    if (medication.isEmpty()) {
        setError(mMedication, R.string.enter_medication);
        valid = false;/* w  w  w .  j ava  2s  .c o m*/
    }
    if (durationDays != null && durationDays == 0) {
        setError(mGiveForDays, R.string.order_give_for_days_cannot_be_zero);
        valid = false;
    }
    Utils.logUserAction("order_submitted", "valid", "" + valid, "uuid", uuid, "medication", medication,
            "dosage", dosage, "frequency", frequency, "instructions", instructions, "durationDays",
            "" + durationDays);

    if (!valid) {
        return;
    }

    dialog.dismiss();

    DateTime now = Utils.getDateTime(getArguments(), "now_millis");
    DateTime start = Utils.getDateTime(getArguments(), "start_millis");
    start = Utils.valueOrDefault(start, now);

    if (durationDays != null) {
        // Adjust durationDays to account for a start date in the past.  Entering "2"
        // always means two more days, stopping after tomorrow, regardless of start date.
        LocalDate firstDay = start.toLocalDate();
        LocalDate lastDay = now.toLocalDate().plusDays(durationDays - 1);
        durationDays = Days.daysBetween(firstDay, lastDay).getDays() + 1;
    }

    // Post an event that triggers the PatientChartController to save the order.
    EventBus.getDefault()
            .post(new OrderSaveRequestedEvent(uuid, patientUuid, instructions, start, durationDays));
}

From source file:org.projectbuendia.client.ui.dialogs.OrderDialogFragment.java

License:Apache License

/** Updates the various labels in the form that react to changes in input fields. */
void updateLabels() {
    DateTime now = Utils.getDateTime(getArguments(), "now_millis");
    String text = mGiveForDays.getText().toString().trim();
    int days = text.isEmpty() ? 0 : Integer.parseInt(text);
    LocalDate lastDay = now.toLocalDate().plusDays(days - 1);
    mGiveForDaysLabel.setText(days == 0 ? R.string.order_give_for_days
            : days == 1 ? R.string.order_give_for_day : R.string.order_give_for_days);
    mDurationLabel.setText(getResources()
            .getString(days == 0 ? R.string.order_duration_unspecified
                    : days == 1 ? R.string.order_duration_stop_after_today
                            : days == 2 ? R.string.order_duration_stop_after_tomorrow
                                    : R.string.order_duration_stop_after_date)
            .replace("%s", Utils.toShortString(lastDay)));
}

From source file:org.projectbuendia.client.ui.dialogs.OrderExecutionDialogFragment.java

License:Apache License

void updateUi(boolean orderExecutedNow) {
    Bundle args = getArguments();//from   w  w w.  j a v a 2s  .  co  m
    LocalDate date = new DateTime(Utils.getLong(args, "intervalStartMillis")).toLocalDate();
    List<DateTime> executionTimes = new ArrayList<>();
    for (long millis : args.getLongArray("executionTimes")) {
        executionTimes.add(new DateTime(millis));
    }

    // Show what was ordered and when the order started.
    mOrderInstructions.setText(args.getString("instructions"));
    DateTime start = Utils.getDateTime(args, "orderStartMillis");
    mOrderStartTime.setText(getResources().getString(R.string.order_started_on_date_at_time,
            Utils.toShortString(start.toLocalDate()), Utils.toTimeOfDayString(start)));

    // Describe how many times the order was executed during the selected interval.
    int count = executionTimes.size() + (orderExecutedNow ? 1 : 0);
    boolean plural = count != 1;
    mOrderExecutionCount.setText(Html.fromHtml(getResources().getString(
            date.equals(LocalDate.now())
                    ? (plural ? R.string.order_execution_today_plural_html
                            : R.string.order_execution_today_singular_html)
                    : (plural ? R.string.order_execution_historical_plural_html
                            : R.string.order_execution_historical_singular_html),
            count, Utils.toShortString(date))));

    // Show the list of times that the order was executed during the selected interval.
    boolean editable = args.getBoolean("editable");
    Utils.showIf(mOrderExecutionList, executionTimes.size() > 0 || editable);
    List<String> htmlItems = new ArrayList<>();
    for (DateTime executionTime : executionTimes) {
        htmlItems.add(Utils.toTimeOfDayString(executionTime));
    }
    if (editable) {
        DateTime encounterTime = Utils.getDateTime(args, "encounterTimeMillis");
        htmlItems.add(
                orderExecutedNow ? "<b>" + Utils.toTimeOfDayString(encounterTime) + "</b>" : "<b>&nbsp;</b>"); // keep total height stable
    }
    mOrderExecutionList.setText(Html.fromHtml(Joiner.on("<br>").join(htmlItems)));
}

From source file:org.slc.sli.common.util.datetime.DateHelper.java

License:Apache License

/**
 * Checks if the DateTime of the first parameter is earlier (or equal to) the second parameter,
 * comparing only the year, month, and day.
 *
 * @param lhs//www. ja v  a  2s  . com
 *            First DateTime.
 * @param rhs
 *            Second DateTime.
 * @return True if first DateTime is before (or equal to) to the second DateTime, false
 *         otherwise.
 */
public boolean isLhsBeforeRhs(DateTime lhs, DateTime rhs) {
    return !rhs.toLocalDate().isBefore(lhs.toLocalDate());
}

From source file:org.solovyev.android.messenger.messages.MessagesMock.java

License:Apache License

@Nonnull
public static Message newMockMessage(@Nonnull DateTime sendDate, @Nonnull Entity from, @Nonnull Entity to,
        @Nonnull String accountId, @Nonnull String chatId) {
    final Message message = mock(Message.class);

    final String id = getMessageId();
    when(message.getEntity()).thenReturn(newEntity(accountId, id));
    when(message.getId()).thenReturn(String.valueOf(id));
    when(message.getBody()).thenReturn("body_" + id);
    when(message.getTitle()).thenReturn("title_" + id);

    when(message.getAuthor()).thenReturn(from);

    when(message.getRecipient()).thenReturn(to);
    when(message.getState()).thenReturn(created);

    when(message.getSendDate()).thenReturn(sendDate);
    final DateTime localDateTime = sendDate.toDateTime(DateTimeZone.forTimeZone(TimeZone.getDefault()));
    when(message.getLocalSendDateTime()).thenReturn(localDateTime);
    when(message.getLocalSendDate()).thenReturn(localDateTime.toLocalDate());
    final MutableAProperties properties = newProperties(Collections.<AProperty>emptyList());
    properties.setProperty("property_1", "test");
    properties.setProperty("property_2", "42");
    when(message.getProperties()).thenReturn(properties);
    when(message.getChat()).thenReturn(newEntityFromEntityId(chatId));
    return message;
}

From source file:org.specrunner.converters.core.ConverterLocalDatePatternArgs.java

License:Open Source License

@Override
public Object convert(Object value, Object[] args) throws ConverterException {
    if (value instanceof LocalDate) {
        return value;
    }/* ww w.j  a  va 2 s.co  m*/
    DateTime date = (DateTime) super.convert(value, args);
    return date != null ? date.toLocalDate() : null;
}