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:org.apache.empire.struts2.jsp.controls.TextInputControl.java

protected DateFormat getDateFormat(DataType dataType, Locale locale, Column column) {
    DateFormat df;/*from   w ww.ja  va2 s  . com*/
    if (dataType == DataType.DATE)
        df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
    else
        df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale);
    return df;
}

From source file:de.betterform.xml.xforms.ui.AbstractFormControl.java

/**
 * convert a localized value into its XML Schema datatype representation. If the value given cannot be parsed with
 * the locale in betterForm context the default locale (US) will be used as fallback. This can be convenient for
 * user-agents that do not pass a localized value back.
 *
 * @param value the value to convert//w  w  w.  j a va 2 s  .c  om
 * @return converted value that can be used to update instance data and match the Schema datatype lexical space
 * @throws java.text.ParseException in case the incoming string cannot be converted into a Schema datatype representation
 */
protected String delocaliseValue(String value) throws XFormsException, ParseException {
    if (value == null || value.equals("")) {
        return value;
    }
    if (Config.getInstance().getProperty(XFormsProcessorImpl.BETTERFORM_ENABLE_L10N).equals("true")) {
        Locale locale = (Locale) getModel().getContainer().getProcessor().getContext()
                .get(XFormsProcessorImpl.BETTERFORM_LOCALE);
        XFormsProcessorImpl processor = this.model.getContainer().getProcessor();

        if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":float")
                || processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":decimal")
                || processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":double")) {

            NumberFormat formatter = NumberFormat.getNumberInstance(locale);
            formatter.setMaximumFractionDigits(Double.SIZE);
            BigDecimal number;

            try {
                number = strictParse(value, locale);
            } catch (ParseException e) {
                LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale);
                return value;
            } catch (NumberFormatException nfe) {
                LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale);
                return value;
            } catch (InputMismatchException ime) {
                LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale);
                return value;
            }
            return number.toPlainString();
        } else if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":date")) {
            DateFormat df = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
            Date d = null;
            try {
                d = df.parse(value);
            } catch (ParseException e) {
                //try the default locale - else fail with ParseException
                df = new SimpleDateFormat("yyyy-MM-dd");
                df.setLenient(false);
                d = df.parse(value);
            }
            df = new SimpleDateFormat("yyyy-MM-dd");
            return df.format(d);
        } else if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":dateTime")) {
            String timezone = "";
            // int position = ;
            if (value.contains("GMT")) {
                timezone = value.substring(value.indexOf("GMT") + 3, value.length());
            } else if (value.contains("+")) {
                timezone = value.substring(value.indexOf("+"), value.length());

            } else if (value.contains("Z")) {
                timezone = "Z";
            }

            DateFormat sf = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale);
            Date d = null;
            try {
                d = sf.parse(value);
            } catch (ParseException e) {
                //try the default locale - else fail with ParseException
                sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                d = null;
                d = sf.parse(value);
            }
            sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            String converted = sf.format(d);
            if (!timezone.equals("")) {
                return converted + timezone;
            }
            return converted;
        }
    }
    return value;
}

From source file:com.mifos.mifosxdroid.online.ClientDetailsFragment.java

/**
 * Use this method to fetch and inflate client details
 * in the fragment//from   ww w  . j a v  a  2s.c om
 */
public void getClientDetails() {
    showProgress(true);
    App.apiManager.getClient(clientId, new Callback<Client>() {
        @Override
        public void success(final Client client, Response response) {
            /* Activity is null - Fragment has been detached; no need to do anything. */
            if (getActivity() == null)
                return;

            if (client != null) {
                setToolbarTitle(getString(R.string.client) + " - " + client.getLastname());
                tv_fullName.setText(client.getDisplayName());
                tv_accountNumber.setText(client.getAccountNo());
                tv_externalId.setText(client.getExternalId());
                if (TextUtils.isEmpty(client.getAccountNo()))
                    rowAccount.setVisibility(GONE);

                if (TextUtils.isEmpty(client.getExternalId()))
                    rowExternal.setVisibility(GONE);

                try {
                    List<Integer> dateObj = client.getActivationDate();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM yyyy");
                    Date date = simpleDateFormat.parse(DateHelper.getDateAsString(dateObj));
                    Locale currentLocale = getResources().getConfiguration().locale;
                    DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, currentLocale);
                    String dateString = df.format(date);
                    tv_activationDate.setText(dateString);

                    if (TextUtils.isEmpty(dateString))
                        rowActivation.setVisibility(GONE);

                } catch (IndexOutOfBoundsException e) {
                    Toast.makeText(getActivity(), getString(R.string.error_client_inactive), Toast.LENGTH_SHORT)
                            .show();
                    tv_activationDate.setText("");
                } catch (ParseException e) {
                    Log.d(TAG, e.getLocalizedMessage());
                }
                tv_office.setText(client.getOfficeName());

                if (TextUtils.isEmpty(client.getOfficeName()))
                    rowOffice.setVisibility(GONE);

                if (client.isImagePresent()) {
                    imageLoadingAsyncTask = new ImageLoadingAsyncTask();
                    imageLoadingAsyncTask.execute(client.getId());
                } else {
                    iv_clientImage.setImageDrawable(
                            ResourcesCompat.getDrawable(getResources(), R.drawable.ic_launcher, null));

                    pb_imageProgressBar.setVisibility(GONE);
                }

                iv_clientImage.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        PopupMenu menu = new PopupMenu(getActivity(), view);
                        menu.getMenuInflater().inflate(R.menu.client_image_popup, menu.getMenu());
                        menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                            @Override
                            public boolean onMenuItemClick(MenuItem menuItem) {
                                switch (menuItem.getItemId()) {
                                case R.id.client_image_capture:
                                    captureClientImage();
                                    break;
                                case R.id.client_image_remove:
                                    deleteClientImage();
                                    break;
                                default:
                                    Log.e("ClientDetailsFragment",
                                            "Unrecognized " + "client " + "image menu item");
                                }
                                return true;
                            }
                        });
                        menu.show();
                    }
                });
                showProgress(false);
                inflateClientsAccounts();
            }
        }

        @Override
        public void failure(RetrofitError retrofitError) {
            Toaster.show(rootView, "Client not found.");
            showProgress(false);
        }
    });
}

From source file:org.eclipse.ebr.maven.AboutFilesUtil.java

public void generateAboutHtmlFile(final SortedMap<Artifact, Model> dependencies, final File outputDirectory)
        throws MojoExecutionException {
    final File aboutHtmlFile = new File(outputDirectory, ABOUT_HTML);
    if (aboutHtmlFile.isFile() && !isForce()) {
        getLog().warn(format("Found existing about.html file at '%s'. %s", aboutHtmlFile,
                REQUIRES_FORCE_TO_OVERRIDE_MESSAGE));
        return;/*  w  w  w  .  j  a v a 2  s. co  m*/
    }

    String aboutHtmlText = readAboutHtmlTemplate();
    aboutHtmlText = StringUtils.replaceEach(aboutHtmlText, new String[] { // @formatter:off
            "@DATE@", "@THIRD_PARTY_INFO@" },
            new String[] { DateFormat.getDateInstance(DateFormat.LONG, Locale.US).format(new Date()),
                    getThirdPartyInfo(dependencies, outputDirectory) });
    // @formatter:on

    try {
        FileUtils.writeStringToFile(aboutHtmlFile, aboutHtmlText, UTF_8);
    } catch (final IOException e) {
        getLog().debug(e);
        throw new MojoExecutionException(
                format("Unable to write about.html file '%s'. %s", aboutHtmlFile, e.getMessage()));
    }
}

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

public static boolean isValidDate(String value) {
    try {/*from w  ww.j a  va  2 s.c o m*/
        SimpleDateFormat shortFormat = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT,
                internalLocale);
        shortFormat.setLenient(false);
        shortFormat.parse(value);
        return true;
    }

    catch (java.text.ParseException e) {
        return false;
    }
}

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

public static java.sql.Date getLocaleDate(String value) {
    if (internalLocale != null && value != null && !value.equals("")) {
        try {/*from  w  w  w .j av  a 2s .  c  o  m*/
            SimpleDateFormat shortFormat = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT,
                    internalLocale);
            shortFormat.setLenient(false);
            String userPattern = shortFormat.toPattern();
            String dbDate = convertUserToDbFmt(value, userPattern);
            return java.sql.Date.valueOf(dbDate);
        } catch (RuntimeException alreadyRuntime) {
            throw alreadyRuntime;
        } catch (Exception e) {
            throw new FrameworkRuntimeException(e);
        }
    } else {
        return null;
    }
}

From source file:com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.java

private Object doConvertToDate(Map<String, Object> context, Object value, Class toType) {
    Date result = null;// w  w w. ja  v  a  2 s.  c  o m

    if (value instanceof String && value != null && ((String) value).length() > 0) {
        String sa = (String) value;
        Locale locale = getLocale(context);

        DateFormat df = null;
        if (java.sql.Time.class == toType) {
            df = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
        } else if (java.sql.Timestamp.class == toType) {
            Date check = null;
            SimpleDateFormat dtfmt = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.SHORT,
                    DateFormat.MEDIUM, locale);
            SimpleDateFormat fullfmt = new SimpleDateFormat(dtfmt.toPattern() + MILLISECOND_FORMAT, locale);

            SimpleDateFormat dfmt = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale);

            SimpleDateFormat[] fmts = { fullfmt, dtfmt, dfmt };
            for (SimpleDateFormat fmt : fmts) {
                try {
                    check = fmt.parse(sa);
                    df = fmt;
                    if (check != null) {
                        break;
                    }
                } catch (ParseException ignore) {
                }
            }
        } else if (java.util.Date.class == toType) {
            Date check = null;
            DateFormat[] dfs = getDateFormats(locale);
            for (DateFormat df1 : dfs) {
                try {
                    check = df1.parse(sa);
                    df = df1;
                    if (check != null) {
                        break;
                    }
                } catch (ParseException ignore) {
                }
            }
        }
        //final fallback for dates without time
        if (df == null) {
            df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
        }
        try {
            df.setLenient(false); // let's use strict parsing (XW-341)
            result = df.parse(sa);
            if (!(Date.class == toType)) {
                try {
                    Constructor constructor = toType.getConstructor(new Class[] { long.class });
                    return constructor.newInstance(new Object[] { Long.valueOf(result.getTime()) });
                } catch (Exception e) {
                    throw new XWorkException(
                            "Couldn't create class " + toType + " using default (long) constructor", e);
                }
            }
        } catch (ParseException e) {
            throw new XWorkException("Could not parse date", e);
        }
    } else if (Date.class.isAssignableFrom(value.getClass())) {
        result = (Date) value;
    }
    return result;
}

From source file:org.hoteia.qalingo.core.service.EmailService.java

/**
 * @throws Exception // w ww  .  j av a  2 s. c  o m
 */
public Email buildAndSaveRetailerContactMail(final RequestData requestData, final Customer customer,
        final String velocityPath, final RetailerContactEmailBean retailerContactEmailBean) throws Exception {
    Email email = null;
    try {
        final String contextNameValue = requestData.getContextNameValue();
        final Localization localization = requestData.getMarketAreaLocalization();
        final Locale locale = localization.getLocale();

        // SANITY CHECK
        checkEmailAddresses(retailerContactEmailBean);

        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(CUSTOMER, customer);
        model.put("retailerContactEmailBean", retailerContactEmailBean);
        model.put(WORDING, coreMessageSource.loadWording(Email.WORDING_SCOPE_EMAIL, locale));

        String fromAddress = handleFromAddress(retailerContactEmailBean.getFromAddress(), contextNameValue);
        String fromName = handleFromName(retailerContactEmailBean.getFromName(), locale);
        String toEmail = retailerContactEmailBean.getToEmail();

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

        email = new Email();
        email.setType(Email.EMAIl_TYPE_RETAILER_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;
    }
    return email;
}

From source file:com.netflix.governator.lifecycle.LifecycleManager.java

private Date parseDate(String configurationName, String value, Configuration configuration) {
    DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
    formatter.setLenient(false);//from   ww  w  .j av a2 s .c om

    try {
        return formatter.parse(value);
    } catch (ParseException e) {
        // ignore as the fallback is the DatattypeConverter.
    }

    try {
        return DatatypeConverter.parseDateTime(value).getTime();
    } catch (IllegalArgumentException e) {
        ignoreTypeMismtachIfConfigured(configuration, configurationName, e);
    }

    return null;
}