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.paris.lutece.plugins.form.utils.FormUtils.java

/**
 * Converts une java.sql.Timestamp date in a String date in a "jj/mm/aaaa" format
 *
 * @param date java.sql.Timestamp date to convert
 * @param locale the locale/*from   ww w  .ja  va 2  s.  c o m*/
 * @return strDate The String date in the short locale format or the emmpty String if the date is null
 * @deprecated
 */
public static String getDateString(Timestamp date, Locale locale) {
    DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale);

    return dateFormat.format(date);
}

From source file:com.idega.block.cal.renderer.AbstractCompactScheduleRenderer.java

/**
 * <p>/*from w  w w  .ja v  a2 s  . com*/
 * Draw the schedule entries in the specified day cell
 * </p>
 * 
 * @param context
 *            the FacesContext
 * @param schedule
 *            the schedule
 * @param day
 *            the day
 * @param writer
 *            the ResponseWriter
 * 
 * @throws IOException
 *             when the entries could not be drawn
 */
protected void writeEntries(FacesContext context, HtmlSchedule schedule, ScheduleDay day, ResponseWriter writer)
        throws IOException {
    //final String clientId = schedule.getClientId(context);
    //final FormInfo parentFormInfo = RendererUtils.findNestingForm(schedule, context);
    //final String formId = parentFormInfo == null ? null : parentFormInfo.getFormName();
    final TreeSet entrySet = new TreeSet(comparator);

    for (Iterator entryIterator = day.iterator(); entryIterator.hasNext();) {
        ScheduleEntry entry = (ScheduleEntry) entryIterator.next();
        entrySet.add(entry);
    }

    for (Iterator entryIterator = entrySet.iterator(); entryIterator.hasNext();) {
        ScheduleEntry entry = (ScheduleEntry) entryIterator.next();
        writer.startElement(HTML.DIV_ELEM, schedule);
        writer.startElement(HTML.DIV_ELEM, schedule);

        if (isSelected(schedule, entry)) {
            writer.writeAttribute(HTML.CLASS_ATTR, getStyleClass(schedule, "selected"), null);
        }

        //compose the CSS style for the entry box
        StringBuffer entryStyle = new StringBuffer();
        entryStyle.append("width: 100%;");
        String entryColor = getEntryRenderer(schedule).getColor(context, schedule, entry,
                isSelected(schedule, entry));
        if (isSelected(schedule, entry) && entryColor != null) {
            entryStyle.append(" background-color: ");
            entryStyle.append(entryColor);
            entryStyle.append(";");
            entryStyle.append(" border-color: ");
            entryStyle.append(entryColor);
            entryStyle.append(";");
        }

        writer.writeAttribute(HTML.STYLE_ATTR, entryStyle.toString(), null);

        // draw the tooltip
        if (showTooltip(schedule)) {
            getEntryRenderer(schedule).renderToolTip(context, writer, schedule, entry,
                    isSelected(schedule, entry));
        }

        if (!isSelected(schedule, entry) && !schedule.isReadonly()) {
            writer.startElement("a", schedule);
            writer.writeAttribute(HTML.CLASS_ATTR, CalendarConstants.SCHEDULE_ENTRY_STYLE_CLASS, null);
            writer.writeAttribute(HTML.HREF_ATTR, "javascript:void(0)", null);
            writer.writeAttribute("entryid", entry.getId(), null);

            DateFormat format;
            String pattern = null;

            if ((pattern != null) && (pattern.length() > 0)) {
                format = new SimpleDateFormat(pattern);
            } else {
                if (context.getApplication().getDefaultLocale() != null) {
                    format = DateFormat.getDateInstance(DateFormat.MEDIUM,
                            context.getApplication().getDefaultLocale());
                } else {
                    format = DateFormat.getDateInstance(DateFormat.MEDIUM);
                }
            }

            String startTime = format.format(entry.getStartTime());
            startTime += " ";
            startTime += entry.getStartTime().getHours();
            startTime += ":";
            if (entry.getStartTime().getMinutes() < 10) {
                startTime += "0";
                startTime += entry.getStartTime().getMinutes();
            } else {
                startTime += entry.getStartTime().getMinutes();
            }

            String endTime = "";
            endTime += entry.getEndTime().getHours();
            endTime += ":";
            if (entry.getEndTime().getMinutes() < 10) {
                endTime += "0";
                endTime += entry.getEndTime().getMinutes();
            } else {
                endTime += entry.getEndTime().getMinutes();
            }
        }

        // draw the content
        getEntryRenderer(schedule).renderContent(context, writer, schedule, day, entry, true,
                isSelected(schedule, entry));

        if (!isSelected(schedule, entry) && !schedule.isReadonly()) {
            writer.endElement("a");
        }

        writer.endElement(HTML.DIV_ELEM);
        writer.endElement(HTML.DIV_ELEM);
    }
}

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

/**
 * Creates a nice localized date String from the given day, month and year Strings.<p>
 * /*from w  w  w  . j  av a 2 s  . c o  m*/
 * @param day the number of the day as String
 * @param month the number of the month as String
 * @param year the number of the year as String
 * @param localeString the current locale String
 * @return nice formatted date string in long mode (e.g. 15. April 2003)
 */
public static String getNiceDate(String day, String month, String year, String localeString) {

    Locale locale = new Locale(localeString.toLowerCase());
    DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, locale);
    Calendar cal = new GregorianCalendar(locale);
    try {
        cal.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day));
    } catch (Exception e) {
        // noop
    }
    return df.format(cal.getTime());
}

From source file:com.mg.framework.utils.MiscUtils.java

/**
 *  ? ?  ?? ?  <code>DATE, DATETIME, TIME</code>
 *
 * @param value     /*from   www  .j av  a2  s.  c o  m*/
 * @param metadata 
 * @param locale   
 * @return ? ?  ? ? ? <code>value == null</code>
 * @throws NullPointerException ? <code>metadata == null</code>
 */
public static String getDateTextRepresentation(Date value, FieldMetadata metadata, Locale locale) {
    if (value == null || DateTimeUtils.isBoundDateValue(value))
        return StringUtils.EMPTY_STRING;
    if (metadata == null)
        return value.toString();

    DateFormat df;
    switch (metadata.getBuiltInType()) {
    case DATE:
        df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
        break;
    case DATETIME:
        df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale);
        break;
    case TIME:
        df = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
        break;
    default:
        return value.toString();
    }
    return df.format(value);
}

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

/**
 * @throws Exception /*from ww  w  .  j  a  v a  2 s  .  co  m*/
 */
public Email buildAndSaveNewsletterSubscriptionConfirmationMail(final RequestData requestData,
        final String velocityPath, final NewsletterEmailBean newsletterEmailBean) throws Exception {
    Email email = null;
    try {
        final String contextNameValue = requestData.getContextNameValue();
        final MarketArea marketArea = requestData.getMarketArea();
        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));
        urlParams.put(RequestConstants.REQUEST_PARAMETER_MARKET_AREA_CODE, marketArea.getCode());
        String unsubscribeUrl = urlService.generateUrl(FoUrls.NEWSLETTER_UNREGISTER, requestData, urlParams);
        String fullUnsubscribeUrl = urlService.buildAbsoluteUrl(requestData, unsubscribeUrl);

        model.put("unsubscribeUrlOrEmail", fullUnsubscribeUrl);

        String fromAddress = handleFromAddress(newsletterEmailBean.getFromAddress(), contextNameValue);
        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_subscription.email_subject", parameters, locale));
        mimeMessagePreparator.setHtmlContent(VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(),
                velocityPath + "newsletter-subscription-confirmation-html-content.vm", model));
        mimeMessagePreparator
                .setPlainTextContent(VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(),
                        velocityPath + "newsletter-subscription-confirmation-text-content.vm", model));

        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;
    }
    return email;
}

From source file:org.linagora.linshare.core.notifications.service.impl.MailBuildingServiceImpl.java

/**
 * Old and ugly code, to be removed./*from w  w  w.  j a  v a 2s . c  o  m*/
 */

private String formatActivationDate(Account account, UploadRequest uploadRequest) {
    Locale locale = account.getJavaExternalMailLocale();
    DateFormat formatter = DateFormat.getDateInstance(DateFormat.FULL, locale);
    return formatter.format(uploadRequest.getActivationDate().getTime());
}

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

/**
 * Format the date based on the locale and convert it to a String to
 * display. Uses DateFormat.SHORT. Example: 2004-12-10 13:20:00 PST
 *
 * Also includes the timezone of the current User if there is one
 *
 * @param date Date to format.// w w  w  .  j  av a2  s.  com
 * @param locale Locale to use for formatting.
 * @return String representation of given date in given locale.
 */
public String formatDate(Date date, Locale locale) {
    // Example: 2004-12-10 13:20:00 PST
    StringBuilder dbuff = new StringBuilder();
    DateFormat dateI = DateFormat.getDateInstance(DateFormat.SHORT, locale);
    dateI.setTimeZone(determineTimeZone());
    DateFormat timeI = DateFormat.getTimeInstance(DateFormat.LONG, locale);
    timeI.setTimeZone(determineTimeZone());

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

    return getDebugVersionOfString(dbuff.toString());
}

From source file:org.linagora.linshare.core.notifications.service.impl.MailBuildingServiceImpl.java

private String formatExpirationDate(Account account, UploadRequest uploadRequest) {
    if (uploadRequest.getExpiryDate() != null) {
        Locale locale = account.getJavaExternalMailLocale();
        DateFormat formatter = DateFormat.getDateInstance(DateFormat.FULL, locale);
        return formatter.format(uploadRequest.getExpiryDate().getTime());
    }//  w  w w  . j  a v  a2 s. c o  m
    return "";
}

From source file:it.attocchi.jsf2.PageBase.java

public String getCurrentLocaleDatePattern() {
    SimpleDateFormat format = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT,
            getCurrentLocale());/*from w  w  w  . ja  v  a 2  s. c  o  m*/
    return format.toLocalizedPattern();
}

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

public static String getDBtoUserFormatString(java.util.Date dbDate, Locale userLocale) {
    // the following line is for 1.1 release and will be removed when date
    // is localized
    userLocale = internalLocale;//from  w  w  w.  j ava  2s  . c  om
    SimpleDateFormat format = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.MEDIUM, userLocale);
    return format.format(dbDate);
}