Example usage for java.text DateFormat getDateInstance

List of usage examples for java.text DateFormat getDateInstance

Introduction

In this page you can find the example usage for java.text DateFormat getDateInstance.

Prototype

public static final DateFormat getDateInstance(int style, Locale aLocale) 

Source Link

Document

Gets the date formatter with the given formatting style for the given locale.

Usage

From source file:fr.hoteia.qalingo.core.service.impl.EmailServiceImpl.java

/**
 * @throws Exception // ww w  .  j  a  v  a 2 s  .c o m
 * @see fr.hoteia.qalingo.core.service.EmailService#buildAndSaveContactMail(Localization localization, Customer customer, String velocityPath, ContactEmailBean contactEmailBean)
 */
public void buildAndSaveContactMail(final RequestData requestData, final String velocityPath,
        final ContactEmailBean contactEmailBean) throws Exception {
    try {
        final Localization localization = requestData.getLocalization();
        final Locale locale = localization.getLocale();

        // SANITY CHECK
        checkEmailAddresses(contactEmailBean);

        Map<String, Object> model = new HashMap<String, Object>();
        String fromEmail = contactEmailBean.getFromEmail();
        String toEmail = contactEmailBean.getToEmail();

        DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.FULL, locale);
        java.sql.Timestamp currentDate = new java.sql.Timestamp((new java.util.Date()).getTime());
        model.put("currentDate", dateFormatter.format(currentDate));
        model.put("contactEmailBean", contactEmailBean);
        model.put("wording", coreMessageSource.loadWording(Email.WORDING_SCOPE_EMAIL, locale));

        MimeMessagePreparatorImpl mimeMessagePreparator = getMimeMessagePreparator(requestData,
                Email.EMAIl_TYPE_CONTACT, model);
        mimeMessagePreparator.setTo(toEmail);
        mimeMessagePreparator.setFrom(fromEmail);
        mimeMessagePreparator.setFromName(coreMessageSource.getMessage("email.common.from_name", locale));
        mimeMessagePreparator.setReplyTo(fromEmail);
        Object[] parameters = { contactEmailBean.getLastname(), contactEmailBean.getFirstname() };
        mimeMessagePreparator
                .setSubject(coreMessageSource.getMessage("email.contact.email_subject", parameters, locale));
        mimeMessagePreparator.setHtmlContent(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                velocityPath + "contact-html-content.vm", model));
        mimeMessagePreparator.setPlainTextContent(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                velocityPath + "contact-text-content.vm", model));

        mimeMessagePreparator.getHtmlContent();

        Email email = new Email();
        email.setType(Email.EMAIl_TYPE_CONTACT);
        email.setStatus(Email.EMAIl_STATUS_PENDING);
        saveOrUpdateEmail(email, mimeMessagePreparator);

    } catch (MailException e) {
        LOG.error("Error, can't save the message :", e);
        throw e;
    } catch (VelocityException e) {
        LOG.error("Error, can't build the message :", e);
        throw e;
    } catch (IOException e) {
        LOG.error("Error, can't serializable the message :", e);
        throw e;
    }
}

From source file:edu.ku.brc.specify.prefs.FormattingPrefsPanel.java

/**
 * /*from  w w w.  ja va 2s. c  o m*/
 */
protected void fillDateFormat() {

    String currentFormat = AppPreferences.getRemote().get("ui.formatting.scrdateformat", null);

    TimeZone tz = TimeZone.getDefault();
    DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
    dateFormatter.setTimeZone(tz);
    String dateStr = dateFormatter.format(Calendar.getInstance().getTime());
    Character ch = null;
    for (int i = 0; i < 10; i++) {
        if (!StringUtils.isNumeric(dateStr.substring(i, i + 1))) {
            ch = dateStr.charAt(i);
            break;
        }
    }

    if (ch != null) {
        boolean skip = false;
        Vector<String> formats = new Vector<String>();
        if (ch == '/') {
            addFormats(formats, '/');
            skip = true;
        }
        if (ch != '.') {
            addFormats(formats, '.');
            skip = true;
        }
        if (ch != '-') {
            addFormats(formats, '-');
            skip = true;
        }

        if (!skip) {
            addFormats(formats, ch);
        }

        int selectedInx = 0;
        int inx = 0;
        DefaultComboBoxModel model = (DefaultComboBoxModel) dateFieldCBX.getModel();
        for (String fmt : formats) {
            model.addElement(fmt);
            if (currentFormat != null && currentFormat.equals(fmt)) {
                selectedInx = inx;
            }
            inx++;
        }
        dateFieldCBX.getComboBox().setSelectedIndex(selectedInx);
    }
}

From source file:org.hoteia.qalingo.core.service.impl.EmailServiceImpl.java

/**
 * @throws Exception //from ww w .j  a  v a2 s . c  o m
 * @see org.hoteia.qalingo.core.service.EmailService#buildAndSaveContactMail(Localization localization, Customer customer, String velocityPath, ContactEmailBean contactEmailBean)
 */
public void buildAndSaveContactMail(final RequestData requestData, final String velocityPath,
        final ContactEmailBean contactEmailBean) throws Exception {
    try {
        final Localization localization = requestData.getMarketAreaLocalization();
        final Locale locale = localization.getLocale();

        // SANITY CHECK
        checkEmailAddresses(contactEmailBean);

        Map<String, Object> model = new HashMap<String, Object>();
        DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.FULL, locale);
        java.sql.Timestamp currentDate = new java.sql.Timestamp((new java.util.Date()).getTime());
        model.put(CURRENT_DATE, dateFormatter.format(currentDate));
        model.put("contactEmailBean", contactEmailBean);
        model.put(WORDING, coreMessageSource.loadWording(Email.WORDING_SCOPE_EMAIL, locale));

        String fromAddress = handleFromAddress(contactEmailBean.getFromAddress(), locale);
        String fromName = handleFromAddress(contactEmailBean.getFromAddress(), locale);
        String toEmail = contactEmailBean.getToEmail();

        MimeMessagePreparatorImpl mimeMessagePreparator = getMimeMessagePreparator(requestData,
                Email.EMAIl_TYPE_CONTACT, model);
        mimeMessagePreparator.setTo(toEmail);
        mimeMessagePreparator.setFrom(fromAddress);
        mimeMessagePreparator.setFromName(fromName);
        mimeMessagePreparator.setReplyTo(fromAddress);
        Object[] parameters = { contactEmailBean.getLastname(), contactEmailBean.getFirstname() };
        mimeMessagePreparator
                .setSubject(coreMessageSource.getMessage("email.contact.email_subject", parameters, locale));
        mimeMessagePreparator.setHtmlContent(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                velocityPath + "contact-html-content.vm", model));
        mimeMessagePreparator.setPlainTextContent(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                velocityPath + "contact-text-content.vm", model));

        mimeMessagePreparator.getHtmlContent();

        Email email = new Email();
        email.setType(Email.EMAIl_TYPE_CONTACT);
        email.setStatus(Email.EMAIl_STATUS_PENDING);
        saveOrUpdateEmail(email, mimeMessagePreparator);

    } catch (MailException e) {
        logger.error("Error, can't save the message :", e);
        throw e;
    } catch (VelocityException e) {
        logger.error("Error, can't build the message :", e);
        throw e;
    } catch (IOException e) {
        logger.error("Error, can't serializable the message :", e);
        throw e;
    }
}

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

public static String getUserLocaleDate(String databaseDate) {
    if (internalLocale != null && databaseDate != null && !databaseDate.equals("")) {
        try {//from w  w w.jav a  2  s .c o m
            SimpleDateFormat shortFormat = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT,
                    internalLocale);
            String userfmt = convertToCurrentDateFormat(shortFormat.toPattern());
            return convertDbToUserFmt(databaseDate, userfmt);
        } catch (FrameworkRuntimeException e) {
            throw e;
        } catch (Exception e) {
            System.out.println("databaseDate=" + databaseDate + ", locale=" + internalLocale);
            throw new FrameworkRuntimeException(e);
        }
    } else {
        return "";
    }
}

From source file:com.carser.viamais.entity.Transaction.java

public void generateReceipt(final OutputStream os, final String template)
        throws IOException, DocumentException {
    reader = new PdfReader(this.getClass().getResourceAsStream("/receipts/" + template));
    stamper = new PdfStamper(reader, os);
    form = stamper.getAcroFields();/*from   w  ww.  j  ava  2  s .  c om*/
    brazilLocale = new Locale("pt", "BR");
    formatter = NumberFormat.getCurrencyInstance(brazilLocale);
    // Customer data
    Customer customer = getCustomer();
    form.setField("CUSTOMER_NAME", customer.getName().toUpperCase());
    form.setField("CUSTOMER_CPF", StringUtil.formatCPF(customer.getCpf()));
    form.setField("CUSTOMER_RG", customer.getRg().toUpperCase());
    // Addres data
    Address address = customer.getAddresses().get(0);
    StringBuilder addressDescription = new StringBuilder();
    addressDescription.append(address.getStreet());
    addressDescription.append(", " + address.getNumber());
    if (address.getComplement() != null) {
        addressDescription.append(", " + address.getComplement());
    }
    form.setField("CUSTOMER_ADDRESS", addressDescription.toString().toUpperCase());
    form.setField("CUSTOMER_DISTRICT", address.getDistrict().toUpperCase());
    form.setField("CUSTOMER_CEP", address.getCep());
    form.setField("CUSTOMER_CITY", address.getCity().toUpperCase());
    form.setField("CUSTOMER_STATE", address.getState().toUpperCase());
    List<Phone> phones = customer.getPhones();
    for (Phone phone : phones) {
        String phoneNumber = StringUtil.formatPhone(Long.valueOf(phone.getPrefix() + "" + phone.getNumber()));
        switch (phone.getType()) {
        case "Celular":
            form.setField("CUSTOMER_CELLPHONE", phoneNumber);
            break;
        case "Residencial":
            form.setField("CUSTOMER_PHONE", phoneNumber);
            break;
        case "Comercial":
            form.setField("CUSTOMER_COMPHONE", phoneNumber);
            break;
        default:
            break;
        }
    }
    // Car data
    Car car = getCar();
    form.setField("CAR_MANUFACTURER", car.getModel().getManufacturer().getName().toUpperCase());
    form.setField("CAR_MODEL", car.getModel().getName().toUpperCase());
    form.setField("CAR_YEAR", car.getYearOfManufacture() + "/" + car.getYearOfModel());
    form.setField("CAR_COLOR", car.getColor().toUpperCase());
    form.setField("CAR_PLATE", car.getLicensePlate().toUpperCase());
    form.setField("CAR_CHASSI", car.getChassi().toUpperCase());
    form.setField("CAR_RENAVAM", car.getRenavam().toUpperCase());
    // Transaction data
    form.setField("CAR_DEPOSIT",
            formatter.format(getDeposit()) + " (" + StringUtil.formatCurrency(getDeposit()) + ")");
    DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.LONG, brazilLocale);
    form.setField("CAR_VALUE",
            formatter.format(getPrice()) + " (" + StringUtil.formatCurrency(getPrice()) + ")");
    form.setField("DATE", dateFormatter.format(new Date()));
    DateFormat deliveryDateFormatter = DateFormat.getDateInstance(DateFormat.SHORT, brazilLocale);
    DateFormat deliveryTimeFormatter = DateFormat.getTimeInstance(DateFormat.SHORT, brazilLocale);
    if (getDeliveryDate() != null) {
        form.setField("DELIVERY_DATE", deliveryDateFormatter.format(getDeliveryDate()) + " "
                + deliveryTimeFormatter.format(getDeliveryDate()));
    }
    if (getKm() != null) {
        form.setField("DELIVERY_KM", getKm().toString());
    }

}

From source file:com.expressui.core.view.field.format.DefaultFormats.java

/**
 * Get date format, using current user's locale and default date style defined in application.properties.
 *
 * @return default date format/*  w  w  w .  ja  va  2s . co m*/
 */
public PropertyFormatter getDateFormat() {
    return new JDKBridgePropertyFormatter(DateFormat.getDateInstance(
            applicationProperties.getDefaultDateStyle(), MainApplication.getInstance().getLocale()));
}

From source file:org.apache.click.util.Format.java

/**
 * Return a formatted current date string using the default DateFormat.
 *
 * @return a formatted date string/*from   w ww .  j ava2s .  c  om*/
 */
public String currentDate() {
    DateFormat format = DateFormat.getDateInstance(DateFormat.DEFAULT, getLocale());

    return format.format(new Date());
}

From source file:com.zextras.modules.chat.server.history.HistoryMailManager.java

public @Nullable Chat findMessage(Date currentDate, SpecificAddress participant)
        throws ZimbraException, MessagingException {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    DateFormat defaultDateFormat = DateFormat.getDateInstance(3, Locale.getDefault());

    Iterator<Item> messages;
    QueryResults queryResults = null;/*w ww . ja  va  2 s  .co m*/
    try {
        String query = "inid:" + Mailbox.ID_FOLDER_IM_LOGS + " date:" + defaultDateFormat.format(currentDate)
                + " subject:\"" + mChatProperties.getProductName() + " - " + participant.toString() + "\"";
        queryResults = mMailbox.search(mMailbox.newOperationContext(), query, new byte[] { Item.TYPE_MESSAGE },
                SortedBy.DATE_DESC, 1);
        messages = buildQueryResultsIterator(queryResults);
    } catch (IOException e) {
        messages = mMailbox.getItemList(Item.TYPE_CHAT, mOperationContext).iterator();
    }

    try {
        while (messages.hasNext()) {
            Item message = messages.next();
            if (message.getFolderId() != Mailbox.ID_FOLDER_IM_LOGS) {
                continue;
            }

            String emailDateFormatted = dateFormat.format(new Date(message.getDate()));

            String subject = message.getSubject();

            String currentDateFormatted = dateFormat.format(currentDate);
            if (!currentDateFormatted.equals(emailDateFormatted)
                    || !subject.endsWith("Chat - " + participant)) {
                continue;
            }

            Chat chat = message.toChat();
            String[] historyVersion = chat.getMimeMessage().getHeader("ZxChat-History-Version");
            Date emailDate = chat.getMimeMessage().getSentDate();

            if (historyVersion == null || emailDate == null) {
                continue;
            }

            if (historyVersion.length > 0 && historyVersion[0].equals(CHAT_HISTORY_VERSION)) {
                return chat;
            }
        }
    } finally {
        IOUtils.closeQuietly(queryResults);
    }

    return null;
}

From source file:fr.free.coup2lapan.ActualStateActivity.java

public BatteryStat getBatteryStatus() {

    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent status = this.registerReceiver(null, ifilter);

    BatteryStat batterystat = new BatteryStat(status.getIntExtra(BatteryManager.EXTRA_LEVEL, 0),
            status.getIntExtra(BatteryManager.EXTRA_SCALE, 0),
            status.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0),
            status.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0),
            status.getIntExtra(BatteryManager.EXTRA_STATUS, 0),
            status.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0),
            status.getIntExtra(BatteryManager.EXTRA_HEALTH, 0),
            status.getExtras().getBoolean(BatteryManager.EXTRA_PRESENT) ? 1 : 0,
            DateFormat.getDateInstance(2, localeFR).format(new Date())
                    + DateFormat.getTimeInstance(2, localeFR).format(new Date()),
            status.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY));

    return batterystat;
}

From source file:org.nuxeo.ecm.core.schema.types.constraints.DateIntervalConstraint.java

@Override
public String getErrorMessage(Object invalidValue, Locale locale) {
    // test whether there's a custom translation for this field constraint specific translation
    // the expected key is label.schema.constraint.violation.[ConstraintName].mininmaxin ou
    // the expected key is label.schema.constraint.violation.[ConstraintName].minexmaxin ou
    // the expected key is label.schema.constraint.violation.[ConstraintName].mininmaxex ou
    // the expected key is label.schema.constraint.violation.[ConstraintName].minexmaxex ou
    // the expected key is label.schema.constraint.violation.[ConstraintName].minin ou
    // the expected key is label.schema.constraint.violation.[ConstraintName].minex ou
    // the expected key is label.schema.constraint.violation.[ConstraintName].maxin ou
    // the expected key is label.schema.constraint.violation.[ConstraintName].maxex
    // follow the AbstractConstraint behavior otherwise
    Locale computedLocale = locale != null ? locale : Constraint.MESSAGES_DEFAULT_LANG;
    Object[] params;//from w  ww  .  j  av a2  s.  c om
    String subKey = (minTime != null ? (includingMin ? "minin" : "minex") : "")
            + (maxTime != null ? (includingMax ? "maxin" : "maxex") : "");
    DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM, computedLocale);
    if (minTime != null && maxTime != null) {
        String min = format.format(new Date(minTime));
        String max = format.format(new Date(maxTime));
        params = new Object[] { min, max };
    } else if (minTime != null) {
        String min = format.format(new Date(minTime));
        params = new Object[] { min };
    } else {
        String max = format.format(new Date(maxTime));
        params = new Object[] { max };
    }
    List<String> pathTokens = new ArrayList<String>();
    pathTokens.add(MESSAGES_KEY);
    pathTokens.add(DateIntervalConstraint.NAME);
    pathTokens.add(subKey);
    String key = StringUtils.join(pathTokens, '.');
    String message = getMessageString(MESSAGES_BUNDLE, key, params, computedLocale);
    if (message != null && !message.trim().isEmpty() && !key.equals(message)) {
        // use a custom constraint message if there's one
        return message;
    } else {
        // follow AbstractConstraint behavior otherwise
        return super.getErrorMessage(invalidValue, computedLocale);
    }
}