Example usage for org.joda.time LocalDate toDateTimeAtStartOfDay

List of usage examples for org.joda.time LocalDate toDateTimeAtStartOfDay

Introduction

In this page you can find the example usage for org.joda.time LocalDate toDateTimeAtStartOfDay.

Prototype

public DateTime toDateTimeAtStartOfDay() 

Source Link

Document

Converts this LocalDate to a full datetime at the earliest valid time for the date using the default time zone.

Usage

From source file:org.mifos.framework.util.helpers.DateUtils.java

License:Open Source License

public static Date getDateFromLocalDate(LocalDate localDate) {
    if (localDate == null) {
        return null;
    }/*  w  ww  . j a  v a2  s . c om*/
    return localDate.toDateTimeAtStartOfDay().toDate();
}

From source file:org.mifosplatform.portfolio.client.domain.Client.java

License:Mozilla Public License

private Client(final AppUser currentUser, final ClientStatus status, final Office office,
        final Group clientParentGroup, final String accountNo, final String firstname, final String middlename,
        final String lastname, final String fullname, final LocalDate activationDate,
        final LocalDate officeJoiningDate, final String externalId, final String mobileNo, final Staff staff,
        final LocalDate submittedOnDate, final SavingsProduct savingsProduct,
        final SavingsAccount savingsAccount, final LocalDate dateOfBirth, final CodeValue gender,
        final CodeValue clientType, final CodeValue clientClassification) {

    if (StringUtils.isBlank(accountNo)) {
        this.accountNumber = new RandomPasswordGenerator(19).generate();
        this.accountNumberRequiresAutoGeneration = true;
    } else {/*from w  ww.j a  va2s.  c o  m*/
        this.accountNumber = accountNo;
    }

    this.submittedOnDate = submittedOnDate.toDate();
    this.submittedBy = currentUser;

    this.status = status.getValue();
    this.office = office;
    if (StringUtils.isNotBlank(externalId)) {
        this.externalId = externalId.trim();
    } else {
        this.externalId = null;
    }

    if (StringUtils.isNotBlank(mobileNo)) {
        this.mobileNo = mobileNo.trim();
    } else {
        this.mobileNo = null;
    }

    if (activationDate != null) {
        this.activationDate = activationDate.toDateTimeAtStartOfDay().toDate();
        this.activatedBy = currentUser;
    }
    if (officeJoiningDate != null) {
        this.officeJoiningDate = officeJoiningDate.toDateTimeAtStartOfDay().toDate();
    }
    if (StringUtils.isNotBlank(firstname)) {
        this.firstname = firstname.trim();
    } else {
        this.firstname = null;
    }

    if (StringUtils.isNotBlank(middlename)) {
        this.middlename = middlename.trim();
    } else {
        this.middlename = null;
    }

    if (StringUtils.isNotBlank(lastname)) {
        this.lastname = lastname.trim();
    } else {
        this.lastname = null;
    }

    if (StringUtils.isNotBlank(fullname)) {
        this.fullname = fullname.trim();
    } else {
        this.fullname = null;
    }

    if (clientParentGroup != null) {
        this.groups = new HashSet<>();
        this.groups.add(clientParentGroup);
    }

    this.staff = staff;
    this.savingsProduct = savingsProduct;
    this.savingsAccount = savingsAccount;

    if (gender != null) {
        this.gender = gender;
    }
    if (dateOfBirth != null) {
        this.dateOfBirth = dateOfBirth.toDateTimeAtStartOfDay().toDate();
    }
    this.clientType = clientType;
    this.clientClassification = clientClassification;

    deriveDisplayName();
    validate();
}

From source file:org.mifosplatform.portfolio.loanproduct.domain.LoanProduct.java

License:Mozilla Public License

public LoanProduct(final Fund fund, final LoanTransactionProcessingStrategy transactionProcessingStrategy,
        final String name, final String shortName, final String description, final MonetaryCurrency currency,
        final BigDecimal defaultPrincipal, final BigDecimal defaultMinPrincipal,
        final BigDecimal defaultMaxPrincipal, final BigDecimal defaultNominalInterestRatePerPeriod,
        final BigDecimal defaultMinNominalInterestRatePerPeriod,
        final BigDecimal defaultMaxNominalInterestRatePerPeriod,
        final PeriodFrequencyType interestPeriodFrequencyType,
        final BigDecimal defaultAnnualNominalInterestRate, final InterestMethod interestMethod,
        final InterestCalculationPeriodMethod interestCalculationPeriodMethod, final Integer repayEvery,
        final PeriodFrequencyType repaymentFrequencyType, final Integer defaultNumberOfInstallments,
        final Integer defaultMinNumberOfInstallments, final Integer defaultMaxNumberOfInstallments,
        final Integer graceOnPrincipalPayment, final Integer graceOnInterestPayment,
        final Integer graceOnInterestCharged, final AmortizationMethod amortizationMethod,
        final BigDecimal inArrearsTolerance, final List<Charge> charges,
        final AccountingRuleType accountingRuleType, final boolean includeInBorrowerCycle,
        final LocalDate startDate, final LocalDate closeDate, final String externalId,
        final boolean useBorrowerCycle,
        final Set<LoanProductBorrowerCycleVariations> loanProductBorrowerCycleVariations,
        final boolean multiDisburseLoan, final Integer maxTrancheCount, final BigDecimal outstandingLoanBalance,
        final Integer graceOnArrearsAgeing, final Integer overdueDaysForNPA,
        final DaysInMonthType daysInMonthType, final DaysInYearType daysInYearType,
        final boolean isInterestRecalculationEnabled,
        final LoanProductInterestRecalculationDetails productInterestRecalculationDetails,
        final Integer minimumDaysBetweenDisbursalAndFirstRepayment, final boolean holdGuarantorFunds,
        final LoanProductGuaranteeDetails loanProductGuaranteeDetails,
        final BigDecimal principalThresholdForLastInstallment,
        final boolean accountMovesOutOfNPAOnlyOnArrearsCompletion, final boolean canDefineEmiAmount,
        final Integer installmentAmountInMultiplesOf,
        final LoanProductConfigurableAttributes loanProductConfigurableAttributes) {
    this.fund = fund;
    this.transactionProcessingStrategy = transactionProcessingStrategy;
    this.name = name.trim();
    this.shortName = shortName.trim();
    if (StringUtils.isNotBlank(description)) {
        this.description = description.trim();
    } else {/*from w w  w  .j  ava 2 s.c  o m*/
        this.description = null;
    }

    if (charges != null) {
        this.charges = charges;
    }

    this.loanProductRelatedDetail = new LoanProductRelatedDetail(currency, defaultPrincipal,
            defaultNominalInterestRatePerPeriod, interestPeriodFrequencyType, defaultAnnualNominalInterestRate,
            interestMethod, interestCalculationPeriodMethod, repayEvery, repaymentFrequencyType,
            defaultNumberOfInstallments, graceOnPrincipalPayment, graceOnInterestPayment,
            graceOnInterestCharged, amortizationMethod, inArrearsTolerance, graceOnArrearsAgeing,
            daysInMonthType.getValue(), daysInYearType.getValue(), isInterestRecalculationEnabled);

    this.loanProductRelatedDetail.validateRepaymentPeriodWithGraceSettings();

    this.loanProductMinMaxConstraints = new LoanProductMinMaxConstraints(defaultMinPrincipal,
            defaultMaxPrincipal, defaultMinNominalInterestRatePerPeriod, defaultMaxNominalInterestRatePerPeriod,
            defaultMinNumberOfInstallments, defaultMaxNumberOfInstallments);

    if (accountingRuleType != null) {
        this.accountingRule = accountingRuleType.getValue();
    }
    this.includeInBorrowerCycle = includeInBorrowerCycle;
    this.useBorrowerCycle = useBorrowerCycle;

    if (startDate != null) {
        this.startDate = startDate.toDateTimeAtStartOfDay().toDate();
    }

    if (closeDate != null) {
        this.closeDate = closeDate.toDateTimeAtStartOfDay().toDate();
    }

    this.externalId = externalId;
    this.borrowerCycleVariations = loanProductBorrowerCycleVariations;
    for (LoanProductBorrowerCycleVariations borrowerCycleVariations : this.borrowerCycleVariations) {
        borrowerCycleVariations.updateLoanProduct(this);
    }
    if (loanProductConfigurableAttributes != null) {
        this.loanConfigurableAttributes = loanProductConfigurableAttributes;
        loanConfigurableAttributes.updateLoanProduct(this);
    }

    this.loanProducTrancheDetails = new LoanProductTrancheDetails(multiDisburseLoan, maxTrancheCount,
            outstandingLoanBalance);
    this.overdueDaysForNPA = overdueDaysForNPA;
    this.productInterestRecalculationDetails = productInterestRecalculationDetails;
    this.minimumDaysBetweenDisbursalAndFirstRepayment = minimumDaysBetweenDisbursalAndFirstRepayment;
    this.holdGuaranteeFunds = holdGuarantorFunds;
    this.loanProductGuaranteeDetails = loanProductGuaranteeDetails;
    this.principalThresholdForLastInstallment = principalThresholdForLastInstallment;
    this.accountMovesOutOfNPAOnlyOnArrearsCompletion = accountMovesOutOfNPAOnlyOnArrearsCompletion;
    this.canDefineInstallmentAmount = canDefineEmiAmount;
    this.installmentAmountInMultiplesOf = installmentAmountInMultiplesOf;
}

From source file:org.mifosplatform.portfolio.pgs.pgsclient.domain.PGSClient.java

License:Mozilla Public License

private PGSClient(final AppUser currentUser, final PGSClientStatus status, final Office office,
        final Group clientParentGroup, final String accountNo, final String firstname, final String middlename,
        final String lastname, final String fullname, final LocalDate activationDate,
        final LocalDate officeJoiningDate, final String externalId, final String mobileNo, final Staff staff,
        final LocalDate submittedOnDate, final SavingsProduct savingsProduct,
        final SavingsAccount savingsAccount, final LocalDate dateOfBirth, final CodeValue gender) {

    if (StringUtils.isBlank(accountNo)) {
        this.accountNumber = new RandomPasswordGenerator(19).generate();
        this.accountNumberRequiresAutoGeneration = true;
    } else {//ww w.j av a  2 s  . c  o m
        this.accountNumber = accountNo;
    }

    this.submittedOnDate = submittedOnDate.toDate();
    this.submittedBy = currentUser;

    this.status = status.getValue();
    this.office = office;
    if (StringUtils.isNotBlank(externalId)) {
        this.externalId = externalId.trim();
    } else {
        this.externalId = null;
    }

    if (StringUtils.isNotBlank(mobileNo)) {
        this.mobileNo = mobileNo.trim();
    } else {
        this.mobileNo = null;
    }

    if (activationDate != null) {
        this.activationDate = activationDate.toDateTimeAtStartOfDay().toDate();
        this.activatedBy = currentUser;
    }
    if (officeJoiningDate != null) {
        this.officeJoiningDate = officeJoiningDate.toDateTimeAtStartOfDay().toDate();
    }
    if (StringUtils.isNotBlank(firstname)) {
        this.firstname = firstname.trim();
    } else {
        this.firstname = null;
    }

    if (StringUtils.isNotBlank(middlename)) {
        this.middlename = middlename.trim();
    } else {
        this.middlename = null;
    }

    if (StringUtils.isNotBlank(lastname)) {
        this.lastname = lastname.trim();
    } else {
        this.lastname = null;
    }

    if (StringUtils.isNotBlank(fullname)) {
        this.fullname = fullname.trim();
    } else {
        this.fullname = null;
    }

    if (clientParentGroup != null) {
        this.groups = new HashSet<Group>();
        this.groups.add(clientParentGroup);
    }

    this.staff = staff;
    this.savingsProduct = savingsProduct;
    this.savingsAccount = savingsAccount;

    if (gender != null) {
        this.gender = gender;
    }
    if (dateOfBirth != null) {
        this.dateOfBirth = dateOfBirth.toDateTimeAtStartOfDay().toDate();
    }

    deriveDisplayName();
    validate();
}

From source file:org.mousephenotype.dcc.exportlibrary.datastructure.converters.DatatypeConverter.java

License:Apache License

public static Calendar parseDate(String lexicalDate) {
    if (lexicalDate == null || lexicalDate.equals("")) {
        logger.trace("parsing is null or empty");
        return null;
    }//  ww  w  .j  a v  a  2  s .  co  m
    logger.trace("parsing date {}", lexicalDate);
    LocalDate localDate = LocalDate.parse(lexicalDate, DateTimeFormat.forPattern(dateXMLpattern));
    return localDate.toDateTimeAtStartOfDay().toGregorianCalendar();
}

From source file:org.ojbc.intermediaries.sn.dao.SubscriptionSearchQueryDAO.java

License:RPL License

/**
 * Create a subscription (or update an existing one) given the input parameters
 * @param subscriptionSystemId// w  ww.j a v  a 2s  .  com
 * @param topic
 * @param startDateString
 * @param endDateString
 * @param subjectIds
 * @param emailAddresses
 * @param offenderName
 * @param subscribingSystemId
 * @param subscriptionQualifier
 * @param reasonCategoryCode
 * @param subscriptionOwner
 * @return the ID of the created (or updated) subscription
 */
public Number subscribe(String subscriptionSystemId, String topic, String startDateString, String endDateString,
        Map<String, String> subjectIds, Set<String> emailAddresses, String offenderName,
        String subscribingSystemId, String subscriptionQualifier, String reasonCategoryCode,
        String subscriptionOwner, LocalDate creationDateTime, String agencyCaseNumber) {

    Number ret = null;

    log.debug("Entering subscribe method");

    // Use the current time as the start date
    Date startDate = null;
    Date endDate = null;

    // If start date is not provided in the subscription message, use current date
    if (StringUtils.isNotBlank(startDateString)) {
        // Create SQL date from the end date string
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

        try {
            java.util.Date utilStartDate = formatter.parse(startDateString.trim());
            startDate = new Date(utilStartDate.getTime());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    } else {
        startDate = new Date(System.currentTimeMillis());
    }

    // Many subscription message will not have end dates so we will need to
    // allow nulls
    if (StringUtils.isNotBlank(endDateString)) {
        // Create SQL date from the end date string
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

        try {
            java.util.Date utilEndDate = formatter.parse(endDateString.trim());
            endDate = new Date(utilEndDate.getTime());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    java.util.Date creationDate = creationDateTime.toDateTimeAtStartOfDay().toDate();

    log.debug("Start Date String: " + startDateString);
    log.debug("End Date String: " + endDateString);
    log.debug("System Name: " + subscribingSystemId);
    log.debug("Subscription System ID: " + subscriptionSystemId);

    log.info("\n\n\n reasonCategoryCode = " + reasonCategoryCode + "\n\n\n");
    if (StringUtils.isEmpty(reasonCategoryCode)) {
        log.warn("\n\n\n reasonCategoryCode empty, so inserting null into db \n\n\n");
        reasonCategoryCode = null;
    }

    String fullyQualifiedTopic = NotificationBrokerUtils.getFullyQualifiedTopic(topic);

    List<Subscription> subscriptions = getSubscriptions(subscriptionSystemId, fullyQualifiedTopic, subjectIds,
            subscribingSystemId, subscriptionOwner);

    // No Record exist, insert a new one
    if (subscriptions.size() == 0) {

        log.debug("No subscriptions exist, inserting new one");

        log.debug("Inserting row into subscription table");

        KeyHolder keyHolder = new GeneratedKeyHolder();
        this.jdbcTemplate.update(buildPreparedInsertStatementCreator(
                "insert into subscription (topic, startDate, endDate, subscribingSystemIdentifier, subscriptionOwner, subjectName, active, subscription_category_code, lastValidationDate, agency_case_number) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                new Object[] { fullyQualifiedTopic.trim(), startDate, endDate, subscribingSystemId.trim(),
                        subscriptionOwner, offenderName.trim(), 1, reasonCategoryCode, creationDate,
                        agencyCaseNumber }),
                keyHolder);

        ret = keyHolder.getKey();
        log.debug("Inserting row into notification_mechanism table");

        for (String emailAddress : emailAddresses) {
            this.jdbcTemplate.update(
                    "insert into notification_mechanism (subscriptionId, notificationMechanismType, notificationAddress) values (?,?,?)",
                    keyHolder.getKey(), NotificationConstants.NOTIFICATION_MECHANISM_EMAIL, emailAddress);
        }

        log.debug("Inserting row(s) into subscription_subject_identifier table");

        for (Map.Entry<String, String> entry : subjectIds.entrySet()) {
            this.jdbcTemplate.update(
                    "insert into subscription_subject_identifier (subscriptionId, identifierName, identifierValue) values (?,?,?)",
                    keyHolder.getKey(), entry.getKey(), entry.getValue());
        }
    }

    // A subscriptions exists, let's update it
    if (subscriptions.size() == 1) {
        log.debug("Ensure that SIDs match before updating subscription");

        log.debug("Updating existing subscription");
        log.debug("Subject Id Map: " + subjectIds);
        log.debug("Email Addresses: " + emailAddresses.toString());

        log.debug("Updating row in subscription table");

        this.jdbcTemplate.update(
                "update subscription set topic=?, startDate=?, endDate=?, subjectName=?, active=1, subscriptionOwner=?, lastValidationDate=? where id=?",
                new Object[] { fullyQualifiedTopic.trim(), startDate, endDate, offenderName.trim(),
                        subscriptionOwner, creationDate, subscriptions.get(0).getId() });

        log.debug("Updating row in notification_mechanism table");

        // We will delete all email addresses associated with the subscription and re-add them
        this.jdbcTemplate.update("delete from notification_mechanism where subscriptionId = ?",
                new Object[] { subscriptions.get(0).getId() });

        for (String emailAddress : emailAddresses) {
            this.jdbcTemplate.update(
                    "insert into notification_mechanism (subscriptionId, notificationMechanismType, notificationAddress) values (?,?,?)",
                    subscriptions.get(0).getId(), NotificationConstants.NOTIFICATION_MECHANISM_EMAIL,
                    emailAddress);
        }

        ret = subscriptions.get(0).getId();

    }

    if (ret != null && CIVIL_SUBSCRIPTION_REASON_CODE.equals(reasonCategoryCode)) {
        subscribeIdentificationTransaction(ret, agencyCaseNumber, endDateString);
    }

    return ret;

}

From source file:org.openmrs.mobile.activities.addeditpatient.AddEditPatientFragment.java

License:Open Source License

private Person createPerson() {
    Person person = new Person();

    // Add address
    PersonAddress address = new PersonAddress();
    address.getPreferred();//ww w .  j  av a 2 s  .  c  o  m

    List<PersonAddress> addresses = new ArrayList<>();
    addresses.add(address);
    person.setAddresses(addresses);

    //Add person attributes
    List<PersonAttribute> personAttributeList = new ArrayList<>(personAttributeMap.values());
    person.setAttributes(personAttributeList);

    // Add names
    PersonName name = new PersonName();
    name.setFamilyName(ViewUtils.getInput(edlname));
    name.setGivenName(ViewUtils.getInput(edfname));
    name.setMiddleName(ViewUtils.getInput(edmname));

    List<PersonName> names = new ArrayList<>();
    names.add(name);
    person.setNames(names);

    // Add gender
    String[] genderChoices = { "M", "F" };
    int index = gen.indexOfChild(context.findViewById(gen.getCheckedRadioButtonId()));
    if (index != -1) {
        person.setGender(genderChoices[index]);
    } else {
        person.setGender(null);
    }

    // Add birthdate
    String birthdate = null;
    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(DateUtils.OPEN_MRS_REQUEST_PATIENT_FORMAT);
    if (ViewUtils.isEmpty(eddob)) {
        if (!StringUtils.isBlank(ViewUtils.getInput(edyr))
                || !StringUtils.isBlank(ViewUtils.getInput(edmonth))) {
            int yearDiff = ViewUtils.isEmpty(edyr) ? 0 : Integer.parseInt(edyr.getText().toString());
            int monthDiff = ViewUtils.isEmpty(edmonth) ? 0 : Integer.parseInt(edmonth.getText().toString());
            LocalDate now = new LocalDate();
            bdt = now.toDateTimeAtStartOfDay().toDateTime();
            bdt = bdt.minusYears(yearDiff);
            bdt = bdt.minusMonths(monthDiff);
            person.setBirthdateEstimated(true);
            birthdate = dateTimeFormatter.print(bdt);
        }
    } else {
        birthdate = dateTimeFormatter.print(bdt);
    }
    person.setBirthdate(birthdate);

    return person;
}

From source file:org.openmrs.mobile.activities.RegisterPatientActivity.java

License:Open Source License

void registerPatient() {
    Person person = new Person();

    PersonAddress address = new PersonAddress();
    address.setAddress1(getInput(edaddr1));
    address.setAddress2(getInput(edaddr2));
    address.setCityVillage(getInput(edcity));
    address.setPostalCode(getInput(edpostal));
    address.setCountry(getInput(edcountry));
    address.setStateProvince(getInput(edstate));
    address.setPreferred(true);/*ww w .j a  va2s .  c om*/

    List<PersonAddress> addresses = new ArrayList<>();
    addresses.add(address);
    person.setAddresses(addresses);

    PersonName name = new PersonName();
    name.setFamilyName(getInput(edlname));
    name.setGivenName(getInput(edfname));
    name.setMiddleName(getInput(edmname));

    List<PersonName> names = new ArrayList<>();
    names.add(name);
    person.setNames(names);

    String[] genderChoices = { "M", "F" };
    int index = gen.indexOfChild(findViewById(gen.getCheckedRadioButtonId()));
    String gender = genderChoices[index];
    person.setGender(gender);

    if (isEmpty(eddob)) {
        int yeardiff = isEmpty(edyr) ? 0 : Integer.parseInt(edyr.getText().toString());
        int mondiff = isEmpty(edmonth) ? 0 : Integer.parseInt(edmonth.getText().toString());
        LocalDate now = new LocalDate();
        bdt = now.toDateTimeAtStartOfDay().toDateTime();
        bdt = bdt.minusYears(yeardiff);
        bdt = bdt.minusMonths(mondiff);
        person.setBirthdateEstimated(true);
        person.setBirthdate(bdt.toString());
    } else {
        person.setBirthdate(bdt.toString());
    }

    final Patient patient = new Patient();
    patient.setPerson(person);
    patient.setUuid(" ");
    new PatientService().registerPatient(patient);

    RegisterPatientActivity.this.finish();
}

From source file:org.projectbuendia.client.utils.date.RelativeDateTimeFormatter.java

License:Apache License

public String format(LocalDate now, LocalDate other) {
    // Ensure DateTimes don't match so that we exclude the 'right now' case.
    return format(now.toDateTimeAtStartOfDay().plusMinutes(1), other.toDateTimeAtStartOfDay());
}

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

License:Apache License

@Nonnull
public static CharSequence getMessageTime(@Nonnull Message message) {
    final DateTimeZone localTimeZone = DateTimeZone.forTimeZone(TimeZone.getDefault());

    final DateTime localSendDateTime = message.getLocalSendDateTime();
    final LocalDate localSendDate = message.getLocalSendDate();

    final LocalDate localToday = now(localTimeZone).toLocalDate();
    final LocalDate localYesterday = localToday.minusDays(1);

    if (localSendDate.toDateTimeAtStartOfDay().compareTo(localToday.toDateTimeAtStartOfDay()) == 0) {
        // today//from ww w  .j a v a 2 s. com
        // print time
        return shortTime().print(localSendDateTime);
    } else if (localSendDate.toDateTimeAtStartOfDay().compareTo(localYesterday.toDateTimeAtStartOfDay()) == 0) {
        // yesterday
        return getApplication().getString(R.string.mpp_yesterday_at) + " "
                + shortTime().print(localSendDateTime);
    } else {
        // the days before yesterday
        return shortDate().print(localSendDateTime) + " " + getApplication().getString(R.string.mpp_at_time)
                + " " + shortTime().print(localSendDateTime);
    }
}