Example usage for java.text SimpleDateFormat toLocalizedPattern

List of usage examples for java.text SimpleDateFormat toLocalizedPattern

Introduction

In this page you can find the example usage for java.text SimpleDateFormat toLocalizedPattern.

Prototype

public String toLocalizedPattern() 

Source Link

Document

Returns a localized pattern string describing this date format.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    SimpleDateFormat formatter = new SimpleDateFormat();

    String date = formatter.format(new Date());
    System.out.println(formatter.toLocalizedPattern());
    System.out.println("date = " + date);
}

From source file:org.openmrs.web.taglib.DatePatternTag.java

/**
 * Does the actual working of printing the date pattern
 * /*from  w ww  .  j ava2  s  .  c  o m*/
 * @see javax.servlet.jsp.tagext.TagSupport#doStartTag()
 */
@Override
public int doStartTag() {

    SimpleDateFormat dateFormat = Context.getDateFormat();

    try {
        String pattern = dateFormat.toLocalizedPattern().toLowerCase();

        if ((localize != null) && "false".equals(localize)) {
            pattern = dateFormat.toPattern().toLowerCase();
        }

        pageContext.getOut().write(pattern);
    } catch (Exception e) {
        log.error("error getting date pattern", e);
    }

    return SKIP_BODY;
}

From source file:org.openmrs.web.taglib.DateTimePatternTag.java

/**
 * Does the actual working of printing the datetime pattern
 * //w  w w  . jav a2s.c  o  m
 * @see javax.servlet.jsp.tagext.TagSupport#doStartTag()
 */
@Override
public int doStartTag() {

    SimpleDateFormat dateTimeFormat = Context.getDateTimeFormat();

    try {
        String pattern = dateTimeFormat.toLocalizedPattern().toLowerCase();

        if ((localize != null) && "false".equals(localize)) {
            pattern = dateTimeFormat.toPattern().toLowerCase();
        }

        pageContext.getOut().write(pattern);
    } catch (Exception e) {
        log.error("error getting datetime pattern", e);
    }

    return SKIP_BODY;
}

From source file:ispok.converter.BirthDateConverter.java

@Override
public Object getAsObject(FacesContext fc, UIComponent uic, String string) {

    logger.trace("Entering getAsObject()");

    Locale locale = fc.getViewRoot().getLocale();

    ResourceBundle rb = ResourceBundle.getBundle("ispok/pres/inter/ispok", locale);

    DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
    SimpleDateFormat sdf = (SimpleDateFormat) df;

    String pattern = sdf.toPattern();
    String localPattern = sdf.toLocalizedPattern();

    logger.debug("pattern: {}", pattern);
    logger.debug("localized pattern: {}", localPattern);

    Date date;//from   ww  w .j  a  v  a2  s. c o  m

    try {
        date = new SimpleDateFormat(pattern).parse(string);
    } catch (ParseException ex) {
        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "invalid date", pattern);
        throw new ConverterException(msg);
    }

    if (date.after(new Date())) {
        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, rb.getString("birthdate_invalid"),
                rb.getString("birthdate_valid_future"));
        throw new ConverterException(msg);
    }

    Calendar c = Calendar.getInstance();
    c.set(1850, 1, 1);

    if (date.before(c.getTime())) {
        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, rb.getString("birthdate_invalid"),
                rb.getString("birthdate_valid_past"));
        throw new ConverterException(msg);
    }

    return date;
}

From source file:org.openmrs.web.taglib.TimePatternTag.java

/**
 * Does the actual working of printing the time pattern
 *
 * @see javax.servlet.jsp.tagext.TagSupport#doStartTag()
 *//*from  w  w  w .jav  a2  s. c  o  m*/
@Override
public int doStartTag() {

    SimpleDateFormat dateFormat = Context.getTimeFormat();

    try {
        String pattern;
        if ((localize != null) && "false".equals(localize)) {
            pattern = dateFormat.toPattern().toLowerCase();
        } else {
            pattern = dateFormat.toLocalizedPattern();
        }

        if (null != format && format.equals("jquery")) {
            pattern = pattern.toLowerCase().replaceAll("a", "TT");
        }
        pageContext.getOut().write(pattern);

    } catch (Exception e) {
        log.error("error getting date pattern", e);
    }

    return SKIP_BODY;
}

From source file:org.pentaho.reporting.libraries.designtime.swing.date.TimeCellEditor.java

public void setDateFormat(final DateFormat timeFormat) {
    if (timeFormat == null) {
        throw new NullPointerException();
    }//  ww w . ja v a  2 s .c o m
    sdf = timeFormat;
    setDate(getCellEditorValue());
    if (timeFormat instanceof SimpleDateFormat) {
        final SimpleDateFormat dateFormat = (SimpleDateFormat) timeFormat;
        setToolTipText(dateFormat.toLocalizedPattern());
    } else {
        setToolTipText(null);
    }
}

From source file:org.pentaho.reporting.libraries.designtime.swing.date.DateCellEditor.java

public void setDateFormat(final DateFormat timeFormat) {
    if (timeFormat == null) {
        throw new NullPointerException();
    }/*from   w  w  w .  j a v a 2s . c om*/

    dateField.setFormatterFactory(new JFormattedTextField.AbstractFormatterFactory() {
        public JFormattedTextField.AbstractFormatter getFormatter(final JFormattedTextField tf) {
            return new DateFormatter(timeFormat) {
                // allow to clear the field
                public Object stringToValue(final String text) throws ParseException {
                    return "".equals(text) ? null : super.stringToValue(text);
                }
            };
        }
    });

    if (timeFormat instanceof SimpleDateFormat) {
        final SimpleDateFormat dateFormat = (SimpleDateFormat) timeFormat;
        setToolTipText(dateFormat.toLocalizedPattern());
    } else {
        setToolTipText(null);
    }
    if (dateChooserPanel != null) {
        setDate(getCellEditorValue());
    }
}

From source file:com.concursive.connect.web.modules.communications.jobs.EmailUpdatesJob.java

/**
 * Process email updates queue/*ww  w  . j  a  va 2 s  . co m*/
 *
 * @param context
 * @throws JobExecutionException
 */
public void execute(JobExecutionContext context) throws JobExecutionException {
    SchedulerContext schedulerContext = null;
    Connection db = null;
    try {
        schedulerContext = context.getScheduler().getContext();
        db = SchedulerUtils.getConnection(schedulerContext);
        ApplicationPrefs prefs = (ApplicationPrefs) schedulerContext.get("ApplicationPrefs");
        ServletContext servletContext = (ServletContext) schedulerContext.get("ServletContext");
        LOG.debug("EmailUpdatesJob triggered...");
        while (true) {
            //Retrieve retrieve the next item from the email_updates_queue that is scheduled for now.
            EmailUpdatesQueueList queueList = new EmailUpdatesQueueList();
            queueList.setScheduledOnly(true);
            queueList.setMax(1);
            queueList.buildList(db);
            if (queueList.size() == 0) {
                LOG.debug("No more scheduled emails to be processed...");
                break;
            } else {
                EmailUpdatesQueue queue = (EmailUpdatesQueue) queueList.get(0);
                //Lock that record by issuing a successful update which updates the status = 1 to status = 2.
                if (EmailUpdatesQueue.lockQueue(queue, db)) {
                    LOG.debug("Processing scheduled email queue...");

                    // User who needs to be sent an email
                    User user = UserUtils.loadUser(queue.getEnteredBy());

                    //Determine the date range to query the activity stream data
                    Timestamp min = queue.getProcessed();
                    Timestamp max = new Timestamp(System.currentTimeMillis());

                    if (min == null) {
                        //set the min value to be queue's entered date to restrict picking up all the records in the system
                        min = queue.getEntered();
                    }

                    Configuration configuration = ApplicationPrefs.getFreemarkerConfiguration(servletContext);
                    // Determine the message to be sent
                    String message = EmailUpdatesUtils.getEmailHTMLMessage(db, prefs, configuration, queue, min,
                            max);

                    if (message != null) {
                        // Use the user's locale to format the date
                        SimpleDateFormat formatter = (SimpleDateFormat) SimpleDateFormat
                                .getDateInstance(DateFormat.SHORT, user.getLocale());
                        formatter.applyPattern(
                                DateUtils.get4DigitYearDateFormat(formatter.toLocalizedPattern()));
                        String date = formatter.format(max);

                        String subject = "";
                        if (queue.getScheduleOften()) {
                            subject = "Activity Updates for " + date + " - Recent updates";
                        } else if (queue.getScheduleDaily()) {
                            subject = "Activity Updates for " + date + " - Daily update";
                        } else if (queue.getScheduleWeekly()) {
                            subject = "Activity Updates for " + date + " - Weekly update";
                        } else if (queue.getScheduleMonthly()) {
                            subject = "Activity Updates for " + date + " - Monthly update";
                        }
                        //Try to send the email
                        LOG.debug("Sending email...");
                        SMTPMessage email = SMTPMessageFactory.createSMTPMessageInstance(prefs.getPrefs());
                        email.setFrom(prefs.get(ApplicationPrefs.EMAILADDRESS));
                        email.addReplyTo(prefs.get(ApplicationPrefs.EMAILADDRESS));
                        email.addTo(user.getEmail());
                        email.setSubject(subject);
                        email.setType("text/html");
                        email.setBody(message);
                        email.send();
                    } else {
                        LOG.debug("No activities to report. Skipping email.");
                    }

                    //Determine the next schedule date and save the schedule date and status=1
                    LOG.debug("Calculating next run date...");
                    queue.calculateNextRunDate(db);

                    //Set the max date to be the queue's processed date
                    LOG.debug("Updating process date...");
                    queue.updateProcessedDate(db, max);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new JobExecutionException(e.getMessage());
    } finally {
        SchedulerUtils.freeConnection(schedulerContext, db);
    }
}

From source file:com.concursive.connect.web.taglibs.DateTimeHandler.java

/**
 * Description of the Method//from   w ww  .  j a  v a 2s. co m
 *
 * @return Description of the Return Value
 * @throws JspException Description of the Exception
 */
public int doStartTag() throws JspException {
    try {
        if (timestamp != null) {
            String timeZone = null;
            Locale locale = null;
            // Retrieve the user's timezone from their session
            User thisUser = (User) pageContext.getSession().getAttribute(Constants.SESSION_USER);
            if (thisUser != null) {
                timeZone = thisUser.getTimeZone();
                locale = thisUser.getLocale();
            }
            if (locale == null) {
                locale = Locale.getDefault();
            }
            // Determine the output type
            if (pattern != null && "relative".equals(pattern)) {
                // Output a relative date
                String relativeDate = DateUtils.createRelativeDate(timestamp);
                if (relativeDate != null) {
                    this.pageContext.getOut().write(relativeDate);
                }
            } else {
                // Format the specified timestamp with the retrieved timezone
                SimpleDateFormat formatter = null;
                if (dateOnly) {
                    formatter = (SimpleDateFormat) SimpleDateFormat.getDateInstance(dateFormat, locale);
                    formatter.applyPattern(DateUtils.get4DigitYearDateFormat(formatter.toLocalizedPattern()));
                } else if (timeOnly) {
                    formatter = (SimpleDateFormat) SimpleDateFormat.getTimeInstance(timeFormat, locale);
                } else {
                    formatter = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance(dateFormat, timeFormat,
                            locale);
                    formatter.applyPattern(DateUtils.get4DigitYearDateFormat(formatter.toLocalizedPattern()));
                }

                // Use a Java formatter pattern
                if (pattern != null) {
                    formatter.applyPattern(pattern);
                }
                // Adjust the date/time based on any timezone
                if (timeZone != null) {
                    java.util.TimeZone tz = java.util.TimeZone.getTimeZone(timeZone);
                    formatter.setTimeZone(tz);
                }
                this.pageContext.getOut().write(formatter.format(timestamp));
            }
        } else {
            //no date found, output default
            this.pageContext.getOut().write(defaultValue);
        }
    } catch (Exception e) {
        LOG.debug("Conversion error", e);
    }
    return SKIP_BODY;
}

From source file:com.money.manager.ex.core.Core.java

public String getDefaultSystemDateFormat() {
    Locale locale = Locale.getDefault();
    SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT, locale);
    String pattern = sdf.toLocalizedPattern();
    // replace date
    if (pattern.contains("dd")) {
        pattern = pattern.replace("dd", "%d");
    } else {/*from   w  ww.  java2  s . c  o  m*/
        pattern = pattern.replace("d", "%d");
    }
    // replace month
    if (pattern.contains("MM")) {
        pattern = pattern.replace("MM", "%m");
    } else {
        pattern = pattern.replace("M", "%m");
    }
    // replace year
    pattern = pattern.replace("yyyy", "%Y");
    pattern = pattern.replace("yy", "%y");
    // check if exists in format definition
    boolean found = false;
    String[] availableDateFormats = getContext().getResources().getStringArray(R.array.date_format_mask);
    for (int i = 0; i < availableDateFormats.length; i++) {
        if (pattern.equals(availableDateFormats[i])) {
            found = true;
            break;
        }
    }

    return found ? pattern : null;
}