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.mifos.framework.util.helpers.DateUtils.java

public static java.sql.Date getLocaleDate(Locale locale, String value) throws InvalidDateException {
    // the following line is for 1.1 release and will be removed when date
    // is localized
    locale = internalLocale;/*  w  w w .j a  v a 2  s  .  c om*/
    java.sql.Date result = null;
    if (locale != null && StringUtils.isNotBlank(value)) {
        SimpleDateFormat shortFormat = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale);
        shortFormat.setLenient(false);
        String userPattern = shortFormat.toPattern();
        String dbDate = convertUserToDbFmt(value, userPattern);
        result = java.sql.Date.valueOf(dbDate);
    }
    return result;
}

From source file:io.bitsquare.gui.util.BSFormatter.java

public String formatDateTime(Date date) {
    if (date != null) {
        DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
        DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
        return dateFormatter.format(date) + " " + timeFormatter.format(date);
    } else {/*from   www  .j av a2 s . co  m*/
        return "";
    }
}

From source file:io.bitsquare.gui.util.BSFormatter.java

public String formatDateTimeSpan(Date dateFrom, Date dateTo) {
    if (dateFrom != null && dateTo != null) {
        DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
        DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
        return dateFormatter.format(dateFrom) + " " + timeFormatter.format(dateFrom) + " - "
                + timeFormatter.format(dateTo);
    } else {//  ww w .ja  v a 2  s  .  co  m
        return "";
    }
}

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

/**
 * @see fr.hoteia.qalingo.core.service.EmailService#saveAndBuildNewsletterUnsubscriptionConfirmationMail(Localization localization, Customer customer, String velocityPath, NewsletterEmailBean newsletterEmailBean)
 *//*from   w ww . j  a v a2 s. co m*/
public void saveAndBuildNewsletterUnsubscriptionConfirmationMail(final RequestData requestData,
        final String velocityPath, final NewsletterEmailBean newsletterEmailBean) throws Exception {
    try {
        final Localization localization = requestData.getLocalization();
        final Locale locale = localization.getLocale();

        // SANITY CHECK
        checkEmailAddresses(newsletterEmailBean);

        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("currentDate", dateFormatter.format(currentDate));
        model.put("newsletterEmailBean", newsletterEmailBean);
        model.put("wording", coreMessageSource.loadWording(Email.WORDING_SCOPE_EMAIL, locale));

        Map<String, String> urlParams = new HashMap<String, String>();
        urlParams.put(RequestConstants.REQUEST_PARAMETER_NEWSLETTER_EMAIL,
                URLEncoder.encode(newsletterEmailBean.getToEmail(), Constants.ANSI));
        String subscribeUrl = urlService.generateUrl(FoUrls.NEWSLETTER_REGISTER, requestData, urlParams);
        model.put("subscribeUrl", urlService.buildAbsoluteUrl(requestData, subscribeUrl));

        String unsubscribeUrl = urlService.generateUrl(FoUrls.NEWSLETTER_UNREGISTER, requestData, urlParams);
        String fullUnsubscribeUrl = urlService.buildAbsoluteUrl(requestData, unsubscribeUrl);

        model.put("unsubscribeUrlOrEmail", fullUnsubscribeUrl);

        String fromEmail = newsletterEmailBean.getFromEmail();
        MimeMessagePreparatorImpl mimeMessagePreparator = getMimeMessagePreparator(requestData,
                Email.EMAIl_TYPE_NEWSLETTER_SUBSCRIPTION, model);
        mimeMessagePreparator.setUnsubscribeUrlOrEmail(fullUnsubscribeUrl);
        mimeMessagePreparator.setTo(newsletterEmailBean.getToEmail());
        mimeMessagePreparator.setFrom(fromEmail);
        mimeMessagePreparator.setFromName(coreMessageSource.getMessage("email.common.from_name", locale));
        mimeMessagePreparator.setReplyTo(fromEmail);
        Object[] parameters = {};
        mimeMessagePreparator.setSubject(coreMessageSource
                .getMessage("email.newsletter_unsubscription.email_subject", parameters, locale));
        mimeMessagePreparator.setHtmlContent(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                velocityPath + "newsletter-unsubscription-confirmation-html-content.vm", model));
        mimeMessagePreparator.setPlainTextContent(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                velocityPath + "newsletter-unsubscription-confirmation-text-content.vm", model));

        Email email = new Email();
        email.setType(Email.EMAIl_TYPE_NEWSLETTER_SUBSCRIPTION);
        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:org.getobjects.foundation.UObject.java

/**
 * Returns a java.util.Date for the given object. This method checks:
 * <ul>/*from   w w  w . j  a v a2  s.c  om*/
 * <li>for null, which is returned as null
 * <li>for Date, which is returned as-is
 * <li>for java.util.Calendar, getTime() will be called and returned
 * <li>for String's. Which will get parsed using the default DateFormat.
 * <li>for Number's, which are treated like ms since 1970
 * </ul>
 * All other objects are checked for a 'dateValue' method, which is then
 * called.
 * 
 * @param _v - some object
 * @param _style the given formatting style. For example, SHORT for "M/d/yy"
 *          in the US locale.
 * @param _locale the given locale.
 * 
 * @return a java.util.Date or null
 */
public static Date dateValue(final Object _v, final int _style, final Locale _locale) {
    if (_v == null)
        return null;

    if (_v instanceof Date)
        return (Date) _v;

    if (_v instanceof Calendar)
        return ((Calendar) _v).getTime();

    if (_v instanceof String) {
        String s = ((String) _v).trim();
        if (s.length() == 0)
            return null;

        /* Rhino hack */
        if ("undefined".equals(s)) {
            log.warn("attempt to extract dateValue from 'undefined' string: " + _v);
            return null;
        }

        DateFormat df = DateFormat.getDateInstance(_style, _locale);
        try {
            return df.parse(s);
        } catch (ParseException _e) {
            _e.printStackTrace();
            log.warn("could not parse string as datevalue: '" + _v + "'");
            return null;
        }
    }

    if (_v instanceof Number)
        return new Date(((Number) _v).longValue());

    /* other object */

    try {
        Method m = _v.getClass().getMethod("dateValue");
        if (m != null) {
            Object v = m.invoke(_v);
            if (v == null)
                return null;
            if (v != _v)
                return UObject.dateValue(v, _style, _locale);
            log.warn("object returned itself in its dateValue() method!: " + v);
            return null;
        }
    } catch (SecurityException e) {
    } catch (NoSuchMethodException e) {
    } catch (IllegalArgumentException e) {
    } catch (IllegalAccessException e) {
    } catch (InvocationTargetException e) {
    }

    // TBD: use log
    System.err.println("WARN: unexpected object in UObject.dateValue(): " + _v);
    return null;
}

From source file:com.alkacon.opencms.documentcenter.NewDocumentsTree.java

/**
 * Creates a nice localized date String from the given String.<p>
 * //w  ww  . j  a  v  a2  s . c o m
 * @param dateLongString the date as String representation of a long value
 * @param localeString the current locale String
 * @return nice formatted date string in long mode (e.g. 15. April 2003)
 */
public static String getNiceDate(String dateLongString, String localeString) {

    Locale locale = new Locale(localeString.toLowerCase());
    DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, locale);
    Calendar cal = new GregorianCalendar(locale);
    try {
        cal.setTimeInMillis(Long.parseLong(dateLongString));
    } catch (Exception e) {
        //noop
    }
    return df.format(cal.getTime());
}

From source file:io.bitsquare.gui.util.BSFormatter.java

public String formatDate(Date date) {
    if (date != null) {
        DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
        return dateFormatter.format(date);
    } else {/* www.j a v  a2  s.  c  o m*/
        return "";
    }
}

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

/**
 * @see org.hoteia.qalingo.core.service.EmailService#saveAndBuildNewsletterUnsubscriptionConfirmationMail(Localization localization, Customer customer, String velocityPath, NewsletterEmailBean newsletterEmailBean)
 *///w  ww.j  av a2 s  . co m
public void saveAndBuildNewsletterUnsubscriptionConfirmationMail(final RequestData requestData,
        final String velocityPath, final NewsletterEmailBean newsletterEmailBean) throws Exception {
    try {
        final Localization localization = requestData.getMarketAreaLocalization();
        final Locale locale = localization.getLocale();

        // SANITY CHECK
        checkEmailAddresses(newsletterEmailBean);

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

        Map<String, String> urlParams = new HashMap<String, String>();
        urlParams.put(RequestConstants.REQUEST_PARAMETER_NEWSLETTER_EMAIL,
                URLEncoder.encode(newsletterEmailBean.getToEmail(), Constants.ANSI));
        String subscribeUrl = urlService.generateUrl(FoUrls.NEWSLETTER_REGISTER, requestData, urlParams);
        model.put("subscribeUrl", urlService.buildAbsoluteUrl(requestData, subscribeUrl));

        String unsubscribeUrl = urlService.generateUrl(FoUrls.NEWSLETTER_UNREGISTER, requestData, urlParams);
        String fullUnsubscribeUrl = urlService.buildAbsoluteUrl(requestData, unsubscribeUrl);

        model.put("unsubscribeUrlOrEmail", fullUnsubscribeUrl);

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

        MimeMessagePreparatorImpl mimeMessagePreparator = getMimeMessagePreparator(requestData,
                Email.EMAIl_TYPE_NEWSLETTER_SUBSCRIPTION, model);
        //           mimeMessagePreparator.setUnsubscribeUrlOrEmail(fullUnsubscribeUrl);
        mimeMessagePreparator.setTo(toEmail);
        mimeMessagePreparator.setFrom(fromAddress);
        mimeMessagePreparator.setFromName(fromName);
        mimeMessagePreparator.setReplyTo(fromAddress);
        Object[] parameters = {};
        mimeMessagePreparator.setSubject(coreMessageSource
                .getMessage("email.newsletter_unsubscription.email_subject", parameters, locale));
        mimeMessagePreparator.setHtmlContent(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                velocityPath + "newsletter-unsubscription-confirmation-html-content.vm", model));
        mimeMessagePreparator.setPlainTextContent(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                velocityPath + "newsletter-unsubscription-confirmation-text-content.vm", model));

        Email email = new Email();
        email.setType(Email.EMAIl_TYPE_NEWSLETTER_SUBSCRIPTION);
        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:com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.java

private DateFormat[] getDateFormats(Locale locale) {
    DateFormat dt1 = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG, locale);
    DateFormat dt2 = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale);
    DateFormat dt3 = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);

    DateFormat d1 = DateFormat.getDateInstance(DateFormat.SHORT, locale);
    DateFormat d2 = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
    DateFormat d3 = DateFormat.getDateInstance(DateFormat.LONG, locale);

    DateFormat rfc3399 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    DateFormat[] dfs = { dt1, dt2, dt3, rfc3399, d1, d2, d3 }; //added RFC 3339 date format (XW-473)
    return dfs;/*from  ww  w  .  j a v a  2  s. com*/
}

From source file:com.redhat.rhn.common.localization.LocalizationService.java

/**
 * Format the date as a short date depending on locale (YYYY-MM-DD in the
 * US)//from  w  w  w.  j av  a2 s  .  co  m
 *
 * @param date Date to be formatted
 * @param locale Locale to use for formatting
 * @return String representation of given date.
 */
public String formatShortDate(Date date, Locale locale) {

    StringBuilder dbuff = new StringBuilder();
    DateFormat dateI = DateFormat.getDateInstance(DateFormat.SHORT, locale);

    dbuff.append(dateI.format(date));

    return getDebugVersionOfString(dbuff.toString());
}