List of usage examples for java.text DateFormat getDateInstance
public static final DateFormat getDateInstance(int style, Locale aLocale)
From source file:org.mifos.config.struts.action.CustomFieldsAction.java
private String changeDefaultValueDateToDBFormat(String defaultValue, Locale locale) throws InvalidDateException { SimpleDateFormat shortFormat = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale); String userfmt = DateUtils.convertToCurrentDateFormat(shortFormat.toPattern()); return DateUtils.convertUserToDbFmt(defaultValue, userfmt); }
From source file:fr.hoteia.qalingo.core.service.impl.EmailServiceImpl.java
/** * @see fr.hoteia.qalingo.core.service.EmailService#saveAndBuildNewsletterSubscriptionnConfirmationMail(Localization localization, Customer customer, String velocityPath, NewsletterEmailBean newsletterEmailBean) *//*from w w w.ja v a 2s. c om*/ public void saveAndBuildNewsletterSubscriptionnConfirmationMail(final RequestData requestData, final String velocityPath, final NewsletterEmailBean newsletterEmailBean) throws Exception { try { final MarketArea marketArea = requestData.getMarketArea(); 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)); 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 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_subscription.email_subject", parameters, locale)); mimeMessagePreparator.setHtmlContent(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, velocityPath + "newsletter-subscription-confirmation-html-content.vm", model)); mimeMessagePreparator.setPlainTextContent(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, velocityPath + "newsletter-subscription-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.streets.commons.util.FastDateFormat.java
/** * <p>Gets a date formatter instance using the specified style, time * zone and locale.</p>//from ww w. java 2 s. c o m * * @param style date style: FULL, LONG, MEDIUM, or SHORT * @param timeZone optional time zone, overrides time zone of * formatted date * @param locale optional locale, overrides system locale * @return a localized standard date formatter * @throws IllegalArgumentException if the Locale has no date * pattern defined */ public static synchronized FastDateFormat getDateInstance(int style, TimeZone timeZone, Locale locale) { Object key = new Integer(style); if (timeZone != null) { key = new Pair(key, timeZone); } if (locale != null) { key = new Pair(key, locale); } FastDateFormat format = (FastDateFormat) cDateInstanceCache.get(key); if (format == null) { if (locale == null) { locale = Locale.getDefault(); } try { SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateInstance(style, locale); String pattern = formatter.toPattern(); format = getInstance(pattern, timeZone, locale); cDateInstanceCache.put(key, format); } catch (ClassCastException ex) { throw new IllegalArgumentException("No date pattern for locale: " + locale); } } return format; }
From source file:org.apache.click.util.Format.java
/** * Return a formatted date string using the given date and the default * DateFormat.// www .j a v a 2s .c o m * <p/> * If the date is null this method will return the * {@link #getEmptyString()} value. * * @param date the date value to format * @return a formatted date string */ public String date(Date date) { if (date != null) { DateFormat format = DateFormat.getDateInstance(DateFormat.DEFAULT, getLocale()); return format.format(date); } else { return getEmptyString(); } }
From source file:com.jeeframework.util.validate.GenericTypeValidator.java
/** * <p>/*from www. ja v a 2 s. c om*/ * * Checks if the field is a valid date. The <code>Locale</code> is used * with <code>java.text.DateFormat</code>. The setLenient method is set to * <code>false</code> for all.</p> * *@param value The value validation is being performed on. *@param locale The Locale to use to parse the date (system default if * null) *@return the converted Date value. */ public static Date formatDate(String value, Locale locale) { Date date = null; if (value == null) { return null; } try { DateFormat formatter = null; if (locale != null) { formatter = DateFormat.getDateInstance(DateFormat.SHORT, locale); } else { formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()); } formatter.setLenient(false); date = formatter.parse(value); } catch (ParseException e) { // Bad date so return null Log log = LogFactory.getLog(GenericTypeValidator.class); if (log.isDebugEnabled()) { log.debug("Date parse failed value=[" + value + "], " + "locale=[" + locale + "] " + e); } } return date; }
From source file:org.nuxeo.ecm.webapp.search.SearchResultsBean.java
public String downloadCSV() throws ClientException { try {/*from w w w. j av a2 s . c o m*/ if (newProviderName == null) { throw new ClientException("providerName not set"); } PagedDocumentsProvider provider = getProvider(newProviderName); HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance() .getExternalContext().getResponse(); response.setContentType("text/csv"); response.setHeader("Content-Disposition", "attachment; filename=\"search_results.csv\""); char separator = Framework.getProperty("org.nuxeo.ecm.webapp.search.csv.separator", ",").charAt(0); char quotechar = Framework.getProperty("org.nuxeo.ecm.webapp.search.csv.quotechar", "\"").charAt(0); String endOfLine = Framework.getProperty("org.nuxeo.ecm.webapp.search.csv.endofline", "\n"); CSVWriter writer = new CSVWriter(response.getWriter(), separator, quotechar, endOfLine); List<FieldWidget> widgetList = searchColumns.getResultColumns(); Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale(); DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale); String[] columnNames = new String[widgetList.size()]; int i = 0; for (FieldWidget widget : widgetList) { String columnName = resourcesAccessor.getMessages().get(widget.getLabel()); columnNames[i++] = columnName; } writer.writeNext(columnNames); // GR dump all pages... why not, but we need to restore current page // number. int currentPage = provider.getCurrentPageIndex(); int pageCount = provider.getNumberOfPages(); for (int page = 0; page < pageCount; page++) { DocumentModelList docModelList = provider.getPage(page); for (DocumentModel docModel : docModelList) { String[] columns = new String[widgetList.size()]; i = 0; for (FieldWidget widget : widgetList) { String fieldSchema = widget.getSchemaName(); String fieldName = widget.getFieldName(); Object value = docModel.getProperty(fieldSchema, fieldName); if (fieldSchema.equals("dublincore") && fieldName.equals("title")) { value = DocumentModelFunctions.titleOrId(docModel); } else if (fieldSchema.equals("ecm") && fieldName.equals("primaryType")) { value = docModel.getType(); } else if (fieldSchema.equals("ecm") && fieldName.equals("currentLifeCycleState")) { value = docModel.getCurrentLifeCycleState(); } else { value = docModel.getProperty(fieldSchema, fieldName); } String stringValue; if (value == null) { stringValue = ""; } else if (value instanceof GregorianCalendar) { GregorianCalendar gValue = (GregorianCalendar) value; stringValue = df.format(gValue.getTime()); } else { stringValue = String.valueOf(value); } columns[i++] = stringValue; } writer.writeNext(columns); } } writer.close(); response.flushBuffer(); FacesContext.getCurrentInstance().responseComplete(); // restoring current page provider.getPage(currentPage); } catch (IOException e) { throw new ClientException("download csv failed", e); } return null; }
From source file:org.nuxeo.ecm.platform.ui.web.tag.fn.Functions.java
/** * Return the date format to handle date taking the user's locale into account. * * @since 5.9.1// w w w.j a v a2 s. c om */ public static String dateFormatter(String formatLength) { // A map to store temporary available date format FacesContext context = FacesContext.getCurrentInstance(); Locale locale = context.getViewRoot().getLocale(); int style = DateFormat.SHORT; String styleString = mapOfDateLength.get(formatLength.toLowerCase()); boolean addCentury = false; if ("shortWithCentury".toLowerCase().equals(styleString)) { addCentury = true; } else { style = Integer.parseInt(styleString); } DateFormat aDateFormat = DateFormat.getDateInstance(style, locale); // Cast to SimpleDateFormat to make "toPattern" method available SimpleDateFormat format = (SimpleDateFormat) aDateFormat; // return the date pattern String pattern = format.toPattern(); if (style == DateFormat.SHORT && addCentury) { // hack to add century on generated pattern pattern = YEAR_PATTERN.matcher(pattern).replaceAll("yyyy"); } return pattern; }
From source file:org.hoteia.qalingo.core.service.impl.EmailServiceImpl.java
/** * @see org.hoteia.qalingo.core.service.EmailService#saveAndBuildNewsletterSubscriptionnConfirmationMail(Localization localization, Customer customer, String velocityPath, NewsletterEmailBean newsletterEmailBean) *///w ww. j a v a2s . c o m public void saveAndBuildNewsletterSubscriptionnConfirmationMail(final RequestData requestData, final String velocityPath, final NewsletterEmailBean newsletterEmailBean) throws Exception { try { 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(), 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_subscription.email_subject", parameters, locale)); mimeMessagePreparator.setHtmlContent(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, velocityPath + "newsletter-subscription-confirmation-html-content.vm", model)); mimeMessagePreparator.setPlainTextContent(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, velocityPath + "newsletter-subscription-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:org.agiso.tempel.Tempel.java
/** * /*w w w .j a v a 2 s . c o m*/ * * @param properties * @throws Exception */ private Map<String, Object> addRuntimeProperties(Map<String, Object> properties) throws Exception { Map<String, Object> props = new HashMap<String, Object>(); // Okrelanie lokalizacji daty/czasu uywanej do wypenienia paramtrw szablonw // zawierajcych dat/czas w formatach DateFormat.SHORT, .MEDIUM, .LONG i .FULL: Locale date_locale; if (properties.containsKey(UP_DATE_LOCALE)) { date_locale = LocaleUtils.toLocale((String) properties.get(UP_DATE_LOCALE)); Locale.setDefault(date_locale); } else { date_locale = Locale.getDefault(); } TimeZone time_zone; if (properties.containsKey(UP_TIME_ZONE)) { time_zone = TimeZone.getTimeZone((String) properties.get(UP_DATE_LOCALE)); TimeZone.setDefault(time_zone); } else { time_zone = TimeZone.getDefault(); } // Wyznaczanie daty, na podstawie ktrej zostan wypenione parametry szablonw // przechowujce dat/czas w formatach DateFormat.SHORT, .MEDIUM, .LONG i .FULL. // Odbywa si w oparciu o wartoci parametrw 'date_format' i 'date'. Parametr // 'date_format' definiuje format uywany do parsowania acucha reprezentujcego // dat okrelon parametrem 'date'. Parametr 'date_format' moe nie by okrelony. // W takiej sytuacji uyty jest format DateFormat.LONG aktywnej lokalizacji (tj. // systemowej, ktra moe by przedefiniowana przez parametr 'date_locale'), ktry // moe by przedefiniowany przez parametry 'date_format_long' i 'time_format_long': Calendar calendar = Calendar.getInstance(date_locale); if (properties.containsKey(RP_DATE)) { String date_string = (String) properties.get(RP_DATE); if (properties.containsKey(RP_DATE_FORMAT)) { String date_format = (String) properties.get(RP_DATE_FORMAT); DateFormat formatter = new SimpleDateFormat(date_format); formatter.setTimeZone(time_zone); calendar.setTime(formatter.parse(date_string)); } else if (properties.containsKey(UP_DATE_FORMAT_LONG) && properties.containsKey(UP_TIME_FORMAT_LONG)) { // TODO: Zaoenie, e format data-czas jest zoony z acucha daty i czasu rozdzelonych spacj: // 'UP_DATE_FORMAT_LONG UP_TIME_FORMAT_LONG' DateFormat formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_LONG) + " " + (String) properties.get(UP_TIME_FORMAT_LONG), date_locale); formatter.setTimeZone(time_zone); calendar.setTime(formatter.parse(date_string)); } else { DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, date_locale); formatter.setTimeZone(time_zone); calendar.setTime(formatter.parse(date_string)); } } // Jeli nie okrelono, wypenianie parametrw przechowujcych poszczeglne // skadniki daty, tj. rok, miesic i dzie: if (!properties.containsKey(TP_YEAR)) { props.put(TP_YEAR, calendar.get(Calendar.YEAR)); } if (!properties.containsKey(TP_MONTH)) { props.put(TP_MONTH, calendar.get(Calendar.MONTH)); } if (!properties.containsKey(TP_DAY)) { props.put(TP_DAY, calendar.get(Calendar.DAY_OF_MONTH)); } // Jeli nie okrelono, wypenianie parametrw przechowujcych dat i czas w // formatach SHORT, MEDIUM, LONG i FULL (na podstawie wyznaczonej lokalizacji): Date date = calendar.getTime(); if (!properties.containsKey(TP_DATE_SHORT)) { DateFormat formatter; if (properties.containsKey(UP_DATE_FORMAT_SHORT)) { formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_SHORT), date_locale); } else { formatter = DateFormat.getDateInstance(DateFormat.SHORT, date_locale); } formatter.setTimeZone(time_zone); props.put(TP_DATE_SHORT, formatter.format(date)); } if (!properties.containsKey(TP_DATE_MEDIUM)) { DateFormat formatter; if (properties.containsKey(UP_DATE_FORMAT_MEDIUM)) { formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_MEDIUM), date_locale); } else { formatter = DateFormat.getDateInstance(DateFormat.MEDIUM, date_locale); } formatter.setTimeZone(time_zone); props.put(TP_DATE_MEDIUM, formatter.format(date)); } if (!properties.containsKey(TP_DATE_LONG)) { DateFormat formatter; if (properties.containsKey(UP_DATE_FORMAT_LONG)) { formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_LONG), date_locale); } else { formatter = DateFormat.getDateInstance(DateFormat.LONG, date_locale); } formatter.setTimeZone(time_zone); props.put(TP_DATE_LONG, formatter.format(date)); } if (!properties.containsKey(TP_DATE_FULL)) { DateFormat formatter; if (properties.containsKey(UP_DATE_FORMAT_FULL)) { formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_FULL), date_locale); } else { formatter = DateFormat.getDateInstance(DateFormat.FULL, date_locale); } formatter.setTimeZone(time_zone); props.put(TP_DATE_FULL, formatter.format(date)); } if (!properties.containsKey(TP_TIME_SHORT)) { DateFormat formatter; if (properties.containsKey(UP_TIME_FORMAT_SHORT)) { formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_SHORT), date_locale); } else { formatter = DateFormat.getTimeInstance(DateFormat.SHORT, date_locale); } formatter.setTimeZone(time_zone); props.put(TP_TIME_SHORT, formatter.format(date)); } if (!properties.containsKey(TP_TIME_MEDIUM)) { DateFormat formatter; if (properties.containsKey(UP_TIME_FORMAT_MEDIUM)) { formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_MEDIUM), date_locale); } else { formatter = DateFormat.getTimeInstance(DateFormat.MEDIUM, date_locale); } formatter.setTimeZone(time_zone); props.put(TP_TIME_MEDIUM, formatter.format(date)); } if (!properties.containsKey(TP_TIME_LONG)) { DateFormat formatter; if (properties.containsKey(UP_TIME_FORMAT_LONG)) { formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_LONG), date_locale); } else { formatter = DateFormat.getTimeInstance(DateFormat.LONG, date_locale); } formatter.setTimeZone(time_zone); props.put(TP_TIME_LONG, formatter.format(date)); } if (!properties.containsKey(TP_TIME_FULL)) { DateFormat formatter; if (properties.containsKey(UP_TIME_FORMAT_FULL)) { formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_FULL), date_locale); } else { formatter = DateFormat.getTimeInstance(DateFormat.FULL, date_locale); } formatter.setTimeZone(time_zone); props.put(TP_TIME_FULL, formatter.format(date)); } return props; }
From source file:org.lingcloud.molva.ocl.util.GenericTypeValidator.java
/** * <p>/*from ww w . j av a 2s . com*/ * * Checks if the field is a valid date. The <code>Locale</code> is used with * <code>java.text.DateFormat</code>. The setLenient method is set to * <code>false</code> for all. * </p> * * @param value * The value validation is being performed on. * @param locale * The Locale to use to parse the date (system default if null) * @return the converted Date value. */ public static Date formatDate(String value, Locale locale) { Date date = null; if (value == null) { return null; } try { DateFormat formatter = null; if (locale != null) { formatter = DateFormat.getDateInstance(DateFormat.SHORT, locale); } else { formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()); } formatter.setLenient(false); date = formatter.parse(value); } catch (ParseException e) { // Bad date so return null if (log.isDebugEnabled()) { log.debug("Date parse failed value=[" + value + "], " + "locale=[" + locale + "] " + e); } } return date; }