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.hoteia.qalingo.core.service.impl.EmailServiceImpl.java

/**
 * @see org.hoteia.qalingo.core.service.EmailService#buildAndSaveRetailerContactMail(Localization localization, Customer customer, String velocityPath, RetailerContactEmailBean retailerContactEmailBean)
 *//*  w w  w  . j av a  2  s  .  com*/
public void buildAndSaveRetailerContactMail(final RequestData requestData, final Customer customer,
        final String velocityPath, final RetailerContactEmailBean retailerContactEmailBean) throws Exception {
    try {
        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(), locale);
        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(velocityEngine,
                velocityPath + "retailer-contact-html-content.vm", model));
        mimeMessagePreparator.setPlainTextContent(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                velocityPath + "retailer-contact-text-content.vm", model));

        Email 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;
    }
}

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

public static String getCurrentDate(Locale locale) throws InvalidDateException {
    // the following line is for 1.1 release and will be removed when date
    // is localized
    locale = internalLocale;//from   w  ww.  j a  v  a2 s .co m
    Calendar currentCalendar = getCurrentDateCalendar();
    java.sql.Date currentDate = new java.sql.Date(currentCalendar.getTimeInMillis());
    SimpleDateFormat format = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale);
    String userfmt = convertToCurrentDateFormat(format.toPattern());
    return convertDbToUserFmt(currentDate.toString(), userfmt);
}

From source file:org.gridgain.grid.tools.license.GridLicenseGeneratorV2.java

/**
 * Gets arguments map from program arguments.
 *
 * @param args Program arguments.//from w w w.j a v  a  2 s.  c  o m
 * @return Arguments map.
 * @throws GridException If any program argument is invalid.
 */
private static Map<String, String> getArgumentsMap(String[] args) throws GridException {
    assert args != null;

    Map<String, String> map = new HashMap<String, String>();

    // Put defaults in (EVAL license).
    map.put("type", "EVL");
    map.put("issue-org", "GridGain Systems");
    map.put("user-org", "GridGain Evaluation");
    map.put("license-note", "Internal Evaluation Only");
    map.put("issue-date", DateFormat.getDateInstance(DateFormat.SHORT, Locale.US).format(new Date()));
    map.put("maintenance-time", "12");
    map.put("max-nodes", "3");
    map.put("max-cpus", "12");

    if (!F.isEmpty(args)) {
        Collection<String> usedKeys = new HashSet<String>();

        for (String s : args) {
            int idx = s.indexOf(SEPARATOR);

            if (idx <= 0)
                throw new GridException("Invalid key-value argument [arg=" + s + "]");

            String key = s.substring(0, idx);

            if (!params.containsKey(key))
                throw new GridException("Unknown argument: " + key);

            if (usedKeys.contains(key))
                throw new GridException("Duplicate argument: " + key);

            usedKeys.add(key);

            String val = s.substring(idx + 1);

            if (val.isEmpty())
                throw new GridException("Argument value can't be empty [key=" + key + "]");

            map.put(key, val);
        }
    }

    return map;
}

From source file:org.apache.ddlutils.platform.SqlBuilder.java

/**
 * Sets the locale that is used for number and date formatting
 * (when printing default values and in generates insert/update/delete
 * statements).//  w  w w  .j a va 2  s  .  c  om
 *
 * @param localeStr The new locale or <code>null</code> if default formatting
 *                  should be used; Format is "language[_country[_variant]]"
 */
public void setValueLocale(String localeStr) {
    if (localeStr != null) {
        int sepPos = localeStr.indexOf('_');
        String language = null;
        String country = null;
        String variant = null;

        if (sepPos > 0) {
            language = localeStr.substring(0, sepPos);
            country = localeStr.substring(sepPos + 1);
            sepPos = country.indexOf('_');
            if (sepPos > 0) {
                variant = country.substring(sepPos + 1);
                country = country.substring(0, sepPos);
            }
        } else {
            language = localeStr;
        }
        if (language != null) {
            Locale locale = null;

            if (variant != null) {
                locale = new Locale(language, country, variant);
            } else if (country != null) {
                locale = new Locale(language, country);
            } else {
                locale = new Locale(language);
            }

            _valueLocale = localeStr;
            setValueDateFormat(DateFormat.getDateInstance(DateFormat.SHORT, locale));
            setValueTimeFormat(DateFormat.getTimeInstance(DateFormat.SHORT, locale));
            setValueNumberFormat(NumberFormat.getNumberInstance(locale));
            return;
        }
    }
    _valueLocale = null;
    setValueDateFormat(null);
    setValueTimeFormat(null);
    setValueNumberFormat(null);
}

From source file:org.exoplatform.platform.portlet.juzu.calendar.CalendarPortletController.java

@Ajax
@Resource/*  ww  w . j  a v a  2  s. c o  m*/
public Response.Content calendarHome() throws Exception {

    displayedCalendar.clear();
    displayedCalendarMap.clear();
    tasksDisplayedList.clear();
    eventsDisplayedList.clear();
    String date_act = null;
    String username = CalendarPortletUtils.getCurrentUser();
    Locale locale = Util.getPortalRequestContext().getLocale();
    String dp = formatDate(locale);
    DateFormat d = new SimpleDateFormat(dp);
    DateFormat dTimezone = DateFormat.getDateInstance(DateFormat.SHORT, locale);
    dTimezone.setCalendar(CalendarPortletUtils.getCurrentCalendar());
    Long date = new Date().getTime();
    int clickNumber = Integer.parseInt(nbclick);
    if (clickNumber != 0)
        date = incDecJour(date, clickNumber);
    Date currentTime = new Date(date);
    // Get Calendar object set to the date and time of the given Date object
    Calendar cal = CalendarPortletUtils.getCurrentCalendar();
    cal.setTime(currentTime);

    // Set time fields to zero
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

    // Put it back in the Date object
    currentTime = cal.getTime();
    date_act = d.format(currentTime);
    Date comp = currentTime;
    String defaultCalendarLabel = "Default";
    String dateLabel = "";
    try {
        ResourceBundle rs = ResourceBundle.getBundle("locale/portlet/calendar/calendar", locale);
        defaultCalendarLabel = EntityEncoder.FULL.encode(rs.getString("UICalendars.label.defaultCalendarId"));
        if (clickNumber == 0)
            dateLabel = rs.getString("today.label") + ": ";
        else if (clickNumber == -1)
            dateLabel = rs.getString("yesterday.label") + ": ";
        else if (clickNumber == 1)
            dateLabel = rs.getString("tomorrow.label") + ": ";
        else
            dateLabel = "";
    } catch (MissingResourceException ex) {
        if (clickNumber == 0)
            dateLabel = "today.label" + ": ";
        else if (clickNumber == -1)
            dateLabel = "yesterday.label" + ": ";
        else if (clickNumber == 1)
            dateLabel = "tomorrow.label" + ": ";
        else
            dateLabel = "";
    }

    EntityEncoder.FULL.encode(dateLabel);
    dateLabel = new StringBuffer(dateLabel).append(date_act).toString();
    if (nonDisplayedCalendarList == null) {
        SettingValue settingNode = settingService_.get(Context.USER, Scope.APPLICATION,
                CalendarPortletUtils.HOME_PAGE_CALENDAR_SETTINGS);
        if ((settingNode != null) && (settingNode.getValue().toString().split(":").length == 2)) {
            nonDisplayedCalendarList = settingNode.getValue().toString().split(":")[1].split(",");
        }
    }
    List<CalendarEvent> userEvents = getEvents(username, cal);
    if ((userEvents != null) && (!userEvents.isEmpty())) {
        Iterator itr = userEvents.iterator();
        while (itr.hasNext()) {
            CalendarEvent event = (CalendarEvent) itr.next();
            Date from = d.parse(dTimezone.format(event.getFromDateTime()));
            Date to = d.parse(dTimezone.format(event.getToDateTime()));
            if ((event.getEventType().equals(CalendarEvent.TYPE_EVENT))
                    && (from.compareTo(d.parse(dTimezone.format(comp))) <= 0)
                    && (to.compareTo(d.parse(dTimezone.format(comp))) >= 0)) {
                if (!CalendarPortletUtils.contains(nonDisplayedCalendarList, event.getCalendarId())) {
                    org.exoplatform.calendar.service.Calendar calendar = calendarService_
                            .getUserCalendar(username, event.getCalendarId());
                    if (calendar == null) {
                        calendar = calendarService_.getGroupCalendar(event.getCalendarId());
                    }
                    if (calendar.getGroups() == null) {
                        if (calendar.getId().equals(Utils.getDefaultCalendarId(username))
                                && calendar.getName().equals(NewUserListener.defaultCalendarName)) {
                            calendar.setName(defaultCalendarLabel);
                        }
                    }
                    eventsDisplayedList.add(event);
                    if (!displayedCalendarMap.containsKey(calendar.getId())) {
                        displayedCalendarMap.put(calendar.getId(), calendar);
                        displayedCalendar.add(calendar);
                    }
                }
            } else if ((event.getEventType().equals(CalendarEvent.TYPE_TASK))
                    && (((from.compareTo(comp) <= 0) && (to.compareTo(comp) >= 0))
                            || ((event.getEventState().equals(CalendarEvent.NEEDS_ACTION))
                                    && (to.compareTo(comp) < 0)))) {
                tasksDisplayedList.add(event);
            }
        }
        Collections.sort(eventsDisplayedList, eventsComparator);
        Collections.sort(tasksDisplayedList, tasksComparator);
    }
    return calendar.with().set("displayedCalendar", displayedCalendar)
            .set("calendarDisplayedMap", displayedCalendarMap).set("eventsDisplayedList", eventsDisplayedList)
            .set("tasksDisplayedList", tasksDisplayedList).set("date_act", dateLabel).ok()
            .withCharset(Tools.UTF_8);
}

From source file:org.olat.user.restapi.UserVOFactory.java

/**
 * Allow the date to be in the localized form or not
 * @param value/*from  w  w w . j  ava2  s .  c om*/
 * @param handler
 * @param locale
 * @return
 */
public static final String formatDbDate(String value, Locale locale) {
    if (!StringHelper.containsNonWhitespace(value)) {
        return value;
    }

    boolean raw = true;
    for (int i = 0; i < value.length(); i++) {
        if (!Character.isDigit(value.charAt(i))) {
            raw = false;
            break;
        }
    }

    if (raw) {
        return value;
    }
    try {
        DateFormat outFormater = new SimpleDateFormat("yyyyMMdd", Locale.GERMAN);
        DateFormat inFormater = DateFormat.getDateInstance(DateFormat.SHORT, locale);
        Date date = inFormater.parse(value);
        value = outFormater.format(date);
    } catch (ParseException e) {
        /* silently failed */
    }
    return value;
}

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

public static String getLocalDateString(DateTime date, Locale locale) throws InvalidDateException {
    // the following line is for 1.1 release and will be removed when date
    // is localized
    locale = internalLocale;//from  w  ww . j a  v  a2s. co m
    Calendar calendar = date.toCalendar(locale);
    java.sql.Date currentDate = new java.sql.Date(calendar.getTimeInMillis());
    SimpleDateFormat format = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale);
    String userfmt = convertToCurrentDateFormat(format.toPattern());
    return convertDbToUserFmt(currentDate.toString(), userfmt);
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.elasticExcel.excelimport.EntityDataImporter.java

/**
 * RuntimePeriod get special handling, because they need two columns for one primitive type.
 * /*from ww  w.  j a v  a  2s  .c o  m*/
 * @param instance
 * @param featureExpression
 * @param startCell
 * @param endCell
 */
private void importRuntimePeriodExpression(UniversalModelExpression instance,
        FeatureExpression<?> featureExpression, Cell startCell, Cell endCell) {

    try {
        Date startDate = (startCell != null) ? startCell.getDateCellValue() : null;
        Date endDate = (endCell != null) ? endCell.getDateCellValue() : null;

        if (startDate == null && endDate == null) {
            return;
        }

        if (startDate != null && endDate != null && startDate.getTime() > endDate.getTime()) {
            DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, UserContext.getCurrentLocale());
            logError("Near cell {0}: RuntimePeriod: from {1} until {2} in instance {3}",
                    ExcelUtils.getFullCellName(startCell), df.format(startDate), df.format(endDate), instance);
        } else {
            RuntimePeriod rt = new RuntimePeriod(startDate, endDate);
            setValue(instance, (PropertyExpression<?>) featureExpression, rt, startCell);
        }
    } catch (Exception e) {
        logError("Near cell {0}: Error importing runtime period in {1}: {2}",
                ExcelUtils.getFullCellName(startCell), instance, e.getMessage());
    }
}

From source file:GuestBookServlet.java

private void printComments(PrintWriter out, Locale loc) throws IOException {
    Connection conn = null;/*from   ww  w .  j ava  2s.c  o m*/

    try {
        DateFormat fmt = DateFormat.getDateInstance(DateFormat.FULL, loc);
        ResultSet results;
        Statement stmt;
        int rows, count;

        conn = DriverManager.getConnection(jdbcURL, connectionProperties);
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        results = stmt.executeQuery("SELECT NAME, EMAIL, CMT_DATE, " + "COMMENT, COMMENT_ID " + "FROM COMMENT "
                + "ORDER BY CMT_DATE");
        out.println("<dl>");
        results.last();
        results.next();
        rows = results.getRow();
        // pick a random row
        rows = random.nextInt() % rows;
        if (rows < 4) {
            // if the random row is less than 4, print the first 4 rows
            results.afterLast();
        } else {
            // otherwise go to the specified row, print the prior 5 rows
            results.absolute(rows);
        }
        count = 0;
        // print up to 5 rows going backwards from the randomly
        // selected row
        while (results.previous() && (count < 5)) {
            String name, email, cmt;
            Date date;

            count++;
            name = results.getString(1);
            if (results.wasNull()) {
                name = "Unknown User";
            }
            email = results.getString(2);
            if (results.wasNull()) {
                email = "user@host";
            }
            date = results.getDate(3);
            if (results.wasNull()) {
                date = new Date((new java.util.Date()).getTime());
            }
            cmt = results.getString(4);
            if (results.wasNull()) {
                cmt = "No comment.";
            }
            out.println("<dt><b>" + name + "</b> (" + email + ") on " + fmt.format(date) + "</dt>");
            cmt = noXML(cmt);
            out.println("<dd> " + cmt + "</dd>");
        }
        out.println("</dl>");
    } catch (SQLException e) {
        out.println("A database error occurred: " + e.getMessage());
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
    }
}

From source file:org.exoplatform.outlook.social.OutlookMessageActivity.java

/**
 * {@inheritDoc}//from   w ww .  ja  v  a 2 s .  c  om
 */
@Override
public String getSummary(Node node) {
    try {
        if (node.isNodeType(OutlookService.MESSAGE_NODETYPE)) {
            String fromEmail = node.getProperty("mso:fromEmail").getString();
            String fromName = node.getProperty("mso:fromName").getString();
            Date time = node.getProperty("mso:created").getDate().getTime();

            Locale userLocale = null;
            RequestContext context = RequestContext.getCurrentInstance();
            OrganizationService orgService = getApplicationComponent(OrganizationService.class);
            try {
                UserProfile userProfile = orgService.getUserProfileHandler()
                        .findUserProfileByName(context.getRemoteUser());
                if (userProfile != null) {
                    String lang = userProfile.getUserInfoMap().get(Constants.USER_LANGUAGE);
                    if (lang != null) {
                        userLocale = LocaleContextInfo.getLocale(lang);
                    }
                } else if (LOG.isDebugEnabled()) {
                    LOG.debug("User profile not found for " + context.getRemoteUser());
                }
            } catch (Exception e) {
                LOG.warn("Error getting user profile for " + context.getRemoteUser(), e);
            }

            if (userLocale == null) {
                // try find locale from user request
                if (PortletRequestContext.class.isAssignableFrom(context.getClass())) {
                    userLocale = ((PortalRequestContext) PortletRequestContext.class.cast(context)
                            .getParentAppRequestContext()).getRequest().getLocale();
                } else if (PortalRequestContext.class.isAssignableFrom(context.getClass())) {
                    userLocale = PortalRequestContext.class.cast(context).getRequest().getLocale();
                }
                if (userLocale == null) {
                    // it's server locale in most cases
                    userLocale = context.getLocale();
                    if (userLocale == null) {
                        userLocale = Locale.ENGLISH;
                    }
                }
            }

            DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, userLocale);
            DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, userLocale);

            ResourceBundle res = context.getApplicationResourceBundle();

            StringBuilder fromLine = new StringBuilder();
            fromLine.append(fromName);
            fromLine.append('<');
            fromLine.append(fromEmail);
            fromLine.append('>');

            StringBuilder summary = new StringBuilder();
            summary.append(res.getString("Outlook.activity.from"));
            summary.append(": <a href='mailto:");
            summary.append(fromEmail);
            summary.append("' target='_top'>");
            summary.append(ContentReader.simpleEscapeHtml(fromLine.toString()));
            summary.append("</a> ");
            summary.append(res.getString("Outlook.activity.on"));
            summary.append(' ');
            summary.append(dateFormat.format(time));
            summary.append(' ');
            summary.append(res.getString("Outlook.activity.at"));
            summary.append(' ');
            summary.append(timeFormat.format(time));

            return summary.toString();
        }
    } catch (RepositoryException e) {
        LOG.warn("Error generating info for Outlook message activity node " + node, e);
    }

    return super.getSummary(node);
}