Example usage for java.text DateFormat SHORT

List of usage examples for java.text DateFormat SHORT

Introduction

In this page you can find the example usage for java.text DateFormat SHORT.

Prototype

int SHORT

To view the source code for java.text DateFormat SHORT.

Click Source Link

Document

Constant for short style pattern.

Usage

From source file:org.sakaiproject.cheftool.VelocityPortletPaneledAction.java

/**
 ** Return a String array containing the "h", "m", "a", or "H" characters (corresponding to hour, minute, am/pm, or 24-hour)
 ** in the locale specific order/*from   ww  w  . ja v  a2s .co  m*/
 **/
public String[] getTimeFormatString() {
    SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getTimeInstance(DateFormat.SHORT, rb.getLocale());
    String format = sdf.toPattern();

    Set<String> formatSet = new LinkedHashSet<String>();
    char curChar;
    char lastChar = 0;
    for (int i = 0; i < format.length(); i++) {
        curChar = format.charAt(i);
        if ((curChar == 'h' || curChar == 'm' || curChar == 'a' || curChar == 'H') && curChar != lastChar) {
            formatSet.add(String.valueOf(curChar));
            lastChar = curChar;
        }
    }

    String[] formatArray = formatSet.toArray(new String[formatSet.size()]);
    if (formatArray.length != DEFAULT_TIME_FORMAT_ARRAY.length
            && formatArray.length != DEFAULT_TIME_FORMAT_ARRAY.length - 1) {
        M_log.warn("Unknown time format string (using default): " + format);
        return DEFAULT_TIME_FORMAT_ARRAY.clone();
    } else {
        return formatArray;
    }
}

From source file:org.inheritsource.service.processengine.ActivitiEngineService.java

public List<CommentFeedItem> getProcessInstanceCommentFeedByActivity(String taskId, Locale locale) {
    List<CommentFeedItem> commentFeedItems = new ArrayList<CommentFeedItem>();
    CommentFeedItem cFItem = null;//  w  w w.  j  a  v  a2s.  c  o m
    Task task = null;
    HistoricTaskInstance historicTask = null;
    String processDefinitionUuid = null;
    String activityDefinitionUuid = null;
    String processInstanceId = null;
    String setActivityLabel = null;
    String processLabel = null;

    try {
        List<Comment> comments = engine.getTaskService().getTaskComments(taskId);

        if (comments != null && comments.size() > 0) {

            // Assume task is present first
            task = engine.getTaskService().createTaskQuery().taskId(taskId).singleResult();

            if (task != null) {
                processDefinitionUuid = task.getProcessDefinitionId();
                activityDefinitionUuid = task.getTaskDefinitionKey();
                processInstanceId = task.getProcessInstanceId();
                setActivityLabel = task.getName();
                processLabel = coordinatriceFacade.getStartFormLabel(task.getProcessInstanceId(), locale);
            } else {
                historicTask = engine.getHistoryService().createHistoricTaskInstanceQuery().taskId(taskId)
                        .singleResult();

                if (historicTask != null) {
                    processDefinitionUuid = historicTask.getProcessDefinitionId();
                    activityDefinitionUuid = historicTask.getTaskDefinitionKey();
                    processInstanceId = historicTask.getProcessInstanceId();
                    setActivityLabel = historicTask.getName();
                    processLabel = coordinatriceFacade.getStartFormLabel(historicTask.getProcessInstanceId(),
                            locale);
                } else {
                    processDefinitionUuid = "";
                    activityDefinitionUuid = "";
                    processInstanceId = "";
                    setActivityLabel = "";
                    processLabel = "";
                }
            }

            for (Comment comment : comments) {

                DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT,
                        locale);
                cFItem = new CommentFeedItem();

                cFItem.setProcessDefinitionUuid(processDefinitionUuid);
                cFItem.setProcessInstanceUuid(processInstanceId);
                cFItem.setProcessLabel(processLabel);
                cFItem.setActivityDefinitionUuid(activityDefinitionUuid);
                cFItem.setActivityInstanceUuid(comment.getTaskId());
                cFItem.setActivityLabel(setActivityLabel);
                cFItem.setTimestamp(comment.getTime());
                cFItem.setTimeStampStr(formatter.format(comment.getTime()));
                cFItem.setMessage(comment.getFullMessage());
                cFItem.setUser(userId2UserInfo(comment.getUserId()));

                commentFeedItems.add(cFItem);
            }
        }
    } catch (Exception e) {
        log.error("Unable to getProcessInstanceCommentFeedByActivity with taskId: " + taskId);
        commentFeedItems = new ArrayList<CommentFeedItem>();
    }
    return commentFeedItems;
}

From source file:com.lp.client.frame.component.PanelDokumentenablage.java

protected void eventActionUpdate(ActionEvent aE, boolean bNeedNoUpdateI) throws Throwable {
    bNewNode = false;/*from w  w w  .  j a  va2s .  c  o m*/

    enableToolsPanelButtons(true, PanelBasis.ACTION_SAVE, PanelBasis.ACTION_DISCARD, BUTTON_SCAN);
    enableToolsPanelButtons(false, PanelBasis.ACTION_NEW, PanelBasis.ACTION_UPDATE);

    if (jcrDocDto.getlSicherheitsstufe() == JCRDocFac.SECURITY_ARCHIV) {
        wtfSchlagworte.setEditable(true);
        if (LPMain.getInstance().isLPAdmin()) {
            wcbSicherheitsstufe.setEnabled(true);
        }
    } else {
        enableAllComponents(this, true);
    }
    tree.setEnabled(false);
    wcbVersteckteAnzeigen.setEnabled(false);
    wtfName.setEditable(false);
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.GERMANY);
    wdfZeitpunkt.setText(df.format(new Timestamp(System.currentTimeMillis())));
    wtfAnleger.setText(personalDto.getCKurzzeichen());
}

From source file:org.openmicroscopy.shoola.util.ui.UIUtilities.java

/**
 * Formats as a <code>String</code> the specified time.
 * /*  ww  w  .j av  a 2  s . c o  m*/
 * @param time The timestamp to format.
 * @return Returns the stringified version of the passed timestamp.
 */
public static String formatShortDateTime(Timestamp time) {
    if (time == null)
        time = getDefaultTimestamp();
    return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(time);
}

From source file:com.lp.client.frame.component.PanelDokumentenablage.java

public void setDefaultsForNew() throws Throwable {
    wtfAnleger.setText(personalDto.getCKurzzeichen());
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.GERMANY);
    wdfZeitpunkt.setText(df.format(new Timestamp(System.currentTimeMillis())));
    wtfFilename.setText(file.getName());
    wtfMIME.setText(Helper.getMime(file.getName()));
    wcbVersteckt.setSelected(false);//  w  ww . j a v a 2s.  c  om
    if (bHatStufe3) {
        wcbSicherheitsstufe.setSelectedItem(JCRDocFac.SECURITY_HIGH);
    } else if (bHatStufe2) {
        wcbSicherheitsstufe.setSelectedItem(JCRDocFac.SECURITY_MEDIUM);
    } else if (bHatStufe1) {
        wcbSicherheitsstufe.setSelectedItem(JCRDocFac.SECURITY_LOW);
    } else if (bHatStufe0) {
        wcbSicherheitsstufe.setSelectedItem(JCRDocFac.SECURITY_NONE);
    }
    wcbSicherheitsstufe.removeItem(JCRDocFac.SECURITY_ARCHIV);
    wcbBelegart.removeItem(JCRDocFac.DEFAULT_ARCHIV_BELEGART);
    wtfBelegnummer.setText(tree.getLastSelectedPathComponent().toString());
    wtfTable.setText(sTable);
    wtfRow.setText(sRow);
    wtfPartner.setText(partnerDto.formatFixTitelName1Name2());

}

From source file:com.concursive.connect.web.modules.wiki.utils.WikiToHTMLUtils.java

public static String toHtmlFormField(CustomFormField field, WikiToHTMLContext context) {
    // Set a default value
    if (field.getValue() == null) {
        field.setValue(field.getDefaultValue());
    }//from www  .j  av  a  2  s .  c o  m
    // Protect against any arbitrary input
    String fieldName = StringUtils.toHtmlValue(field.getName());
    // Return output based on type
    switch (field.getType()) {
    case CustomFormField.TEXTAREA:
        String textAreaValue = StringUtils.replace(field.getValue(), "^", CRLF);
        return ("<textarea cols=\"" + field.getColumns() + "\" rows=\"" + field.getRows() + "\" name=\""
                + fieldName + "\">" + StringUtils.toString(textAreaValue) + "</textarea>");
    case CustomFormField.SELECT:
        LookupList lookupList = field.getLookupList();
        int selectedItemId = -1;
        for (LookupElement thisElement : lookupList) {
            if (field.getValue().equals(thisElement.getDescription())) {
                selectedItemId = thisElement.getCode();
            }
        }
        return lookupList.getHtmlSelect(fieldName, selectedItemId);
    case CustomFormField.CHECKBOX:
        return ("<input type=\"checkbox\" name=\"" + fieldName + "\" value=\"ON\" "
                + ("true".equals(field.getValue()) ? "checked" : "") + ">");
    case CustomFormField.CALENDAR:
        String calendarValue = field.getValue();
        if (StringUtils.hasText(calendarValue)) {
            try {
                String convertedDate = DateUtils.getUserToServerDateTimeString(null, DateFormat.SHORT,
                        DateFormat.LONG, field.getValue());
                Timestamp timestamp = DatabaseUtils.parseTimestamp(convertedDate);
                Locale locale = Locale.getDefault();
                int dateFormat = DateFormat.SHORT;
                SimpleDateFormat dateFormatter = (SimpleDateFormat) SimpleDateFormat.getDateInstance(dateFormat,
                        locale);
                calendarValue = dateFormatter.format(timestamp);
            } catch (Exception e) {
                LOG.error("toHtmlFormField calendar", e);
            }
        }
        // Output with a calendar control
        String language = System.getProperty("LANGUAGE");
        String country = System.getProperty("COUNTRY");
        return ("<input type=\"text\" name=\"" + fieldName + "\" id=\"" + fieldName + "\" size=\"10\" value=\""
                + StringUtils.toHtmlValue(calendarValue) + "\" > "
                + "<a href=\"javascript:popCalendar('inputForm', '" + fieldName + "','" + language + "','"
                + country + "');\">" + "<img src=\"" + context.getServerUrl()
                + "/images/icons/stock_form-date-field-16.gif\" "
                + "border=\"0\" align=\"absmiddle\" height=\"16\" width=\"16\"/></a>");
    case CustomFormField.PERCENT:
        return ("<input type=\"text\" name=\"" + fieldName + "\" size=\"5\" value=\""
                + StringUtils.toHtmlValue(field.getValue()) + "\"> " + "%");
    case CustomFormField.INTEGER:
        // Determine the value to display in the field
        String integerValue = StringUtils.toHtmlValue(field.getValue());
        if (StringUtils.hasText(integerValue)) {
            try {
                NumberFormat formatter = NumberFormat.getInstance();
                integerValue = formatter.format(StringUtils.getIntegerNumber(field.getValue()));
            } catch (Exception e) {
                LOG.warn("Could not format integer: " + field.getValue());
            }
        }
        return ("<input type=\"text\" name=\"" + fieldName + "\" size=\"8\" value=\"" + integerValue + "\"> ");
    case CustomFormField.FLOAT:
        // Determine the value to display in the field
        String decimalValue = StringUtils.toHtmlValue(field.getValue());
        if (StringUtils.hasText(decimalValue)) {
            try {
                NumberFormat formatter = NumberFormat.getInstance();
                decimalValue = formatter.format(StringUtils.getDoubleNumber(field.getValue()));
            } catch (Exception e) {
                LOG.warn("Could not decimal format: " + field.getValue());
            }
        }
        return ("<input type=\"text\" name=\"" + fieldName + "\" size=\"8\" value=\"" + decimalValue + "\"> ");
    case CustomFormField.CURRENCY:
        // Use a currencyCode for formatting
        String currencyCode = field.getValueCurrency();
        if (currencyCode == null) {
            currencyCode = field.getCurrency();
        }
        if (!StringUtils.hasText(currencyCode)) {
            currencyCode = "USD";
        }
        HtmlSelect currencyCodeList = HtmlSelectCurrencyCode.getSelect(fieldName + "Currency", currencyCode);
        // Determine the valut to display in the field
        String currencyValue = StringUtils.toHtmlValue(field.getValue());
        if (StringUtils.hasText(currencyValue)) {
            try {
                NumberFormat formatter = NumberFormat.getNumberInstance();
                formatter.setMaximumFractionDigits(2);
                currencyValue = formatter.format(StringUtils.getDoubleNumber(field.getValue()));
            } catch (Exception e) {
                LOG.warn("Could not currencyCode format: " + field.getValue());
            }
        }
        return (currencyCodeList.getHtml() + "<input type=\"text\" name=\"" + fieldName
                + "\" size=\"8\" value=\"" + currencyValue + "\"> ");
    case CustomFormField.EMAIL:
        return ("<input type=\"text\" " + "name=\"" + fieldName + "\" maxlength=\"255\" size=\"40\" value=\""
                + StringUtils.toHtmlValue(field.getValue()) + "\" />");
    case CustomFormField.PHONE:
        return ("<input type=\"text\" " + "name=\"" + fieldName + "\" maxlength=\"60\" size=\"20\" value=\""
                + StringUtils.toHtmlValue(field.getValue()) + "\" />");
    case CustomFormField.URL:
        String value = StringUtils.toHtmlValue(field.getValue());
        if (StringUtils.hasText(value)) {
            if (!value.contains("://")) {
                value = "http://" + field.getValue();
            }
        }
        return ("<input type=\"text\" " + "name=\"" + fieldName + "\" maxlength=\"255\" size=\"40\" value=\""
                + StringUtils.toHtmlValue(value) + "\" />");
    default:
        int maxlength = field.getMaxLength();
        int size = -1;
        if (maxlength > -1) {
            if (maxlength > 40) {
                size = 40;
            } else {
                size = maxlength;
            }
        }
        return ("<input type=\"text\" " + "name=\"" + fieldName + "\" "
                + (maxlength == -1 ? "" : "maxlength=\"" + maxlength + "\" ")
                + (size == -1 ? "" : "size=\"" + size + "\" ") + "value=\""
                + StringUtils.toHtmlValue(field.getValue()) + "\" />");
    }
}

From source file:org.openmrs.util.OpenmrsUtil.java

/**
 * Get the current user's date format Will look similar to "mm-dd-yyyy". Depends on user's
 * locale.//from w  w w. ja  v  a  2s. com
 * 
 * @return a simple date format
 * @should return a pattern with four y characters in it
 * @should not allow the returned SimpleDateFormat to be modified
 * @since 1.5
 */
public static SimpleDateFormat getDateFormat(Locale locale) {
    if (dateFormatCache.containsKey(locale)) {
        return (SimpleDateFormat) dateFormatCache.get(locale).clone();
    }

    // note that we are using the custom OpenmrsDateFormat class here which prevents erroneous parsing of 2-digit years
    SimpleDateFormat sdf = new OpenmrsDateFormat(
            (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale), locale);
    String pattern = sdf.toPattern();

    if (!pattern.contains("yyyy")) {
        // otherwise, change the pattern to be a four digit year
        pattern = pattern.replaceFirst("yy", "yyyy");
        sdf.applyPattern(pattern);
    }
    if (!pattern.contains("MM")) {
        // change the pattern to be a two digit month
        pattern = pattern.replaceFirst("M", "MM");
        sdf.applyPattern(pattern);
    }
    if (!pattern.contains("dd")) {
        // change the pattern to be a two digit day
        pattern = pattern.replaceFirst("d", "dd");
        sdf.applyPattern(pattern);
    }

    dateFormatCache.put(locale, sdf);

    return (SimpleDateFormat) sdf.clone();
}

From source file:org.gvnix.web.screen.roo.addon.SeleniumServicesImpl.java

/**
 * Get test value for a field.//from  w  ww . j a v a  2s.  c o  m
 * 
 * @param field Field to auto generate a value
 * @param random Should be the initialized value generated randomly ?
 * @return Field test value
 */
private String convertToInitializer(FieldMetadata field, boolean random) {

    String initializer = " ";

    short index = 1;
    if (random) {
        index = (short) RANDOM_GENERATOR.nextInt();
    }

    AnnotationMetadata min = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(),
            new JavaType("javax.validation.constraints.Min"));
    if (min != null) {
        AnnotationAttributeValue<?> value = min.getAttribute(new JavaSymbolName("value"));
        if (value != null) {
            index = Short.valueOf(value.getValue().toString());
        }
    }
    if (field.getFieldName().getSymbolName().contains("email")
            || field.getFieldName().getSymbolName().contains("Email")) {
        initializer = "some@email.com";
    } else if (field.getFieldType().equals(JavaType.STRING)) {
        initializer = "some" + field.getFieldName().getSymbolNameCapitalisedFirstLetter() + index;
    } else if (field.getFieldType().equals(new JavaType(Date.class.getName()))
            || field.getFieldType().equals(new JavaType(Calendar.class.getName()))) {
        Calendar cal = Calendar.getInstance();
        AnnotationMetadata dateTimeFormat = null;
        String style = null;
        if (null != (dateTimeFormat = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(),
                new JavaType("org.springframework.format.annotation.DateTimeFormat")))) {
            AnnotationAttributeValue<?> value = dateTimeFormat.getAttribute(new JavaSymbolName("style"));
            if (value != null) {
                style = value.getValue().toString();
            }
        }
        if (null != MemberFindingUtils.getAnnotationOfType(field.getAnnotations(),
                new JavaType("javax.validation.constraints.Past"))) {
            cal.add(Calendar.YEAR, -1);
            cal.add(Calendar.MONTH, -1);
            cal.add(Calendar.DAY_OF_MONTH, -1);
        } else if (null != MemberFindingUtils.getAnnotationOfType(field.getAnnotations(),
                new JavaType("javax.validation.constraints.Future"))) {
            cal.add(Calendar.YEAR, +1);
            cal.add(Calendar.MONTH, +1);
            cal.add(Calendar.DAY_OF_MONTH, +1);
        }
        if (style != null) {
            if (style.startsWith("-")) {
                initializer = ((SimpleDateFormat) DateFormat
                        .getTimeInstance(DateTime.parseDateFormat(style.charAt(1)), Locale.getDefault()))
                                .format(cal.getTime());
            } else if (style.endsWith("-")) {
                initializer = ((SimpleDateFormat) DateFormat
                        .getDateInstance(DateTime.parseDateFormat(style.charAt(0)), Locale.getDefault()))
                                .format(cal.getTime());
            } else {
                initializer = ((SimpleDateFormat) DateFormat.getDateTimeInstance(
                        DateTime.parseDateFormat(style.charAt(0)), DateTime.parseDateFormat(style.charAt(1)),
                        Locale.getDefault())).format(cal.getTime());
            }
        } else {
            initializer = ((SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()))
                    .format(cal.getTime());
        }

    } else if (field.getFieldType().equals(JavaType.BOOLEAN_OBJECT)
            || field.getFieldType().equals(JavaType.BOOLEAN_PRIMITIVE)) {
        initializer = Boolean.FALSE.toString();
    } else if (field.getFieldType().equals(JavaType.INT_OBJECT)
            || field.getFieldType().equals(JavaType.INT_PRIMITIVE)) {
        initializer = Integer.valueOf(index).toString();
    } else if (field.getFieldType().equals(JavaType.DOUBLE_OBJECT)
            || field.getFieldType().equals(JavaType.DOUBLE_PRIMITIVE)) {
        initializer = Double.valueOf(index).toString();
    } else if (field.getFieldType().equals(JavaType.FLOAT_OBJECT)
            || field.getFieldType().equals(JavaType.FLOAT_PRIMITIVE)) {
        initializer = Float.valueOf(index).toString();
    } else if (field.getFieldType().equals(JavaType.LONG_OBJECT)
            || field.getFieldType().equals(JavaType.LONG_PRIMITIVE)) {
        initializer = Long.valueOf(index).toString();
    } else if (field.getFieldType().equals(JavaType.SHORT_OBJECT)
            || field.getFieldType().equals(JavaType.SHORT_PRIMITIVE)) {
        initializer = Short.valueOf(index).toString();
    } else if (field.getFieldType().equals(new JavaType("java.math.BigDecimal"))) {
        initializer = BigDecimal.valueOf(index).toString();
    }
    return initializer;
}

From source file:com.concursive.connect.web.modules.wiki.utils.WikiPDFUtils.java

public static String getFieldValue(WikiPDFContext context, CustomFormField field) {
    // Return output based on type
    switch (field.getType()) {
    case CustomFormField.TEXTAREA:
        return StringUtils.replace(field.getValue(), "^", CRLF);
    case CustomFormField.SELECT:
        return field.getValue();
    case CustomFormField.CHECKBOX:
        if ("true".equals(field.getValue())) {
            return "Yes";
        } else {//  w w w .  j  av a  2  s .c  o  m
            return "No";
        }
    case CustomFormField.CALENDAR:
        String calendarValue = field.getValue();
        if (StringUtils.hasText(calendarValue)) {
            try {
                String convertedDate = DateUtils.getUserToServerDateTimeString(null, DateFormat.SHORT,
                        DateFormat.LONG, field.getValue());
                Timestamp timestamp = DatabaseUtils.parseTimestamp(convertedDate);
                Locale locale = Locale.getDefault();
                int dateFormat = DateFormat.SHORT;
                SimpleDateFormat dateFormatter = (SimpleDateFormat) SimpleDateFormat.getDateInstance(dateFormat,
                        locale);
                calendarValue = dateFormatter.format(timestamp);
            } catch (Exception e) {
                LOG.error(e);
            }
        }
        return calendarValue;
    case CustomFormField.PERCENT:
        return field.getValue() + "%";
    case CustomFormField.INTEGER:
        // Determine the value to display in the field
        String integerValue = StringUtils.toHtmlValue(field.getValue());
        if (StringUtils.hasText(integerValue)) {
            try {
                NumberFormat formatter = NumberFormat.getInstance();
                integerValue = formatter.format(StringUtils.getIntegerNumber(field.getValue()));
            } catch (Exception e) {
                LOG.warn("Could not integer format: " + field.getValue());
            }
        }
        return integerValue;
    case CustomFormField.FLOAT:
        // Determine the value to display in the field
        String decimalValue = field.getValue();
        if (StringUtils.hasText(decimalValue)) {
            try {
                NumberFormat formatter = NumberFormat.getInstance();
                decimalValue = formatter.format(StringUtils.getDoubleNumber(field.getValue()));
            } catch (Exception e) {
                LOG.warn("Could not decimal format: " + field.getValue());
            }
        }
        return decimalValue;
    case CustomFormField.CURRENCY:
        // Use a currency for formatting
        String currencyCode = field.getValueCurrency();
        if (currencyCode == null) {
            currencyCode = field.getCurrency();
        }
        if (!StringUtils.hasText(currencyCode)) {
            currencyCode = "USD";
        }
        try {
            NumberFormat formatter = NumberFormat.getCurrencyInstance();
            if (currencyCode != null) {
                Currency currency = Currency.getInstance(currencyCode);
                formatter.setCurrency(currency);
            }
            return (formatter.format(StringUtils.getDoubleNumber(field.getValue())));
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }
        return field.getValue();
    case CustomFormField.EMAIL:
        return field.getValue();
    case CustomFormField.PHONE:
        PhoneNumberBean phone = new PhoneNumberBean();
        phone.setNumber(field.getValue());
        PhoneNumberUtils.format(phone, Locale.getDefault());
        return phone.toString();
    case CustomFormField.URL:
        String value = StringUtils.toHtmlValue(field.getValue());
        if (StringUtils.hasText(value)) {
            if (!value.contains("://")) {
                value = "http://" + value;
            }
            if (value.contains("://")) {
                return value;
            }
        }
        return value;
    case CustomFormField.IMAGE:
        String image = field.getValue();
        if (StringUtils.hasText(image)) {
            return "WikiImage:" + image;
        }
        return image;
    default:
        return field.getValue();
    }
}

From source file:org.openmrs.util.OpenmrsUtil.java

/**
 * Get the current user's time format Will look similar to "hh:mm a". Depends on user's locale.
 * /* w  w w  . j  ava2  s .co m*/
 * @return a simple time format
 * @should return a pattern with two h characters in it
 * @should not allow the returned SimpleDateFormat to be modified
 * @since 1.9
 */
public static SimpleDateFormat getTimeFormat(Locale locale) {
    if (timeFormatCache.containsKey(locale)) {
        return (SimpleDateFormat) timeFormatCache.get(locale).clone();
    }

    SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getTimeInstance(DateFormat.SHORT, locale);
    String pattern = sdf.toPattern();

    if (!(pattern.contains("hh") || pattern.contains("HH"))) {
        // otherwise, change the pattern to be a two digit hour
        pattern = pattern.replaceFirst("h", "hh").replaceFirst("H", "HH");
        sdf.applyPattern(pattern);
    }

    timeFormatCache.put(locale, sdf);

    return (SimpleDateFormat) sdf.clone();
}