Example usage for java.text SimpleDateFormat toPattern

List of usage examples for java.text SimpleDateFormat toPattern

Introduction

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

Prototype

public String toPattern() 

Source Link

Document

Returns a pattern string describing this date format.

Usage

From source file:net.sf.housekeeper.swing.FoodEditorView.java

/**
 * Creates a JSpinner which uses the current locale's short format for
 * displaying a date. It's default date date is set to today's date.
 * /*from  w  w w. j ava 2  s.  c  o  m*/
 * @return The created spinner.
 */
private JSpinner createDateSpinner() {
    final SpinnerDateModel model = new SpinnerDateModel();

    //Need to truncate the current date for correct spinner operation
    model.setStart(DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH));
    model.setCalendarField(Calendar.DAY_OF_MONTH);

    final JSpinner spinner = new JSpinner(model);

    //Set the spinner's editor to use the current locale's short date
    // format
    final SimpleDateFormat dateFormat = (SimpleDateFormat) SimpleDateFormat.getDateInstance(DateFormat.SHORT);
    final String formatPattern = dateFormat.toPattern();
    spinner.setEditor(new JSpinner.DateEditor(spinner, formatPattern));

    return spinner;
}

From source file:graph.module.DateParseModule.java

@SuppressWarnings("deprecation")
private DAGNode parseDate(SimpleDateFormat sdf, String dateStr) {
    try {/*w w  w .j a  v a  2  s . co m*/
        ParsePosition position = new ParsePosition(0);
        Date date = sdf.parse(dateStr, position);
        if (position.getIndex() != dateStr.length()) {
            // Throw an exception or whatever else you want to do
            return null;
        }
        String pattern = sdf.toPattern();

        StringBuilder buffer = new StringBuilder();
        boolean addFurther = false;
        int brackets = 0;
        if (addFurther || pattern.contains("d")) {
            addFurther = true;
            buffer.append("(" + CommonConcepts.DAYFN.getID() + " '" + date.getDate() + " ");
            brackets++;
        }
        if (addFurther || pattern.contains("M")) {
            addFurther = true;
            buffer.append("(" + CommonConcepts.MONTHFN.getID() + " " + MONTH_FORMATTER.format(date) + " ");
            brackets++;
        }
        if (pattern.contains("y")) {
            buffer.append("(" + CommonConcepts.YEARFN.getID() + " '" + (date.getYear() + 1900));
            brackets++;
        } else if (addFurther)
            buffer.append(CommonConcepts.THE_YEAR.getID());
        for (int i = 0; i < brackets; i++)
            buffer.append(")");
        return (DAGNode) dag_.findOrCreateNode(buffer.toString(), null);
    } catch (Exception e) {
    }
    return null;
}

From source file:org.xwiki.xar.internal.property.DateXarObjectPropertySerializer.java

@Override
public Object read(XMLStreamReader reader) throws XMLStreamException {
    String value = reader.getElementText();

    if (StringUtils.isEmpty(value)) {
        return null;
    }//from  w  ww  .ja  va 2  s  . c om

    // FIXME: The value of a date property should be serialized using the date timestamp or the date format
    // specified in the XClass the date property belongs to.
    SimpleDateFormat sdf = DEFAULT_FORMAT;
    try {
        return sdf.parse(value);
    } catch (ParseException e) {
        // I suppose this is a date format used a long time ago. DateProperty is using the above date format now.
        SimpleDateFormat sdfOld = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy", Locale.US);
        this.logger.warn("Failed to parse date [{}] using format [{}]. Trying again with format [{}].", value,
                sdf.toPattern(), sdfOld.toPattern());
        try {
            return sdfOld.parse(value);
        } catch (ParseException exception) {
            this.logger.warn("Failed to parse date [{}] using format [{}]. Defaulting to the current date.",
                    value, sdfOld.toPattern());
            return new Date();
        }
    }
}

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:org.itracker.model.IssueField.java

private String formatDate(ResourceBundle bundle) {
    assert (dateValue != null) : "dateValue failed";
    try {/*from  w w  w.j a  va2s. c  o  m*/

        SimpleDateFormat sdf = new SimpleDateFormat(
                bundle.getString("itracker.dateformat." + customField.getDateFormat()), bundle.getLocale());

        if (log.isDebugEnabled()) {
            log.debug("getValue: dateFormat from itracker configuration " + sdf.toPattern());
        }

        // sdf = new SimpleDateFormat(dateFormat, locale);
        String formattedDate = sdf.format(this.dateValue);
        if (log.isDebugEnabled()) {
            log.debug("getValue: formated date " + this.dateValue + " to " + formattedDate);
        }
        return formattedDate;
    } catch (NullPointerException ne) {
        log.debug("getValue: ", ne);
        if (dateValue == null) {
            log.warn("getValue: failed to format date, null for " + customField);
        }
        return "";
    }
}

From source file:action.OnlineBookingAction.java

@Actions({
        @Action(value = "/mobile", results = {
                @Result(name = "success", location = "/WEB-INF/jsp/online/widget1.jsp"),
                @Result(name = "input", location = "/WEB-INF/jsp/online/validationError.jsp") }),
        @Action(value = "/goOnlineBookingCalendar", results = {
                @Result(name = "success", location = "/WEB-INF/jsp/online/widget1.jsp"),
                @Result(name = "input", location = "/WEB-INF/jsp/online/validationError.jsp") }) })
public String goOnlineBookingCalendar() {
    Booking booking = null;//w w  w. j  a v a2s .  c  o  m
    Structure structure = null;
    Locale locale = null;
    SimpleDateFormat sdf = null;
    String datePattern = null;
    locale = this.getLocale();
    sdf = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale);
    datePattern = sdf.toPattern();
    this.getSession().put("datePattern", datePattern);
    structure = this.getStructureService().findStructureById(this.getIdStructure());
    this.setStructure(structure);

    booking = new Booking();
    booking.setStatus("online");
    booking.setId_structure(structure.getId());
    this.getSession().put("onlineBooking", booking);
    this.getSession().put("structure", structure);
    this.setBooking(booking);
    return SUCCESS;
}

From source file:org.wso2.carbon.registry.jcr.nodetype.RegistryNodeType.java

public boolean isValidDate(String inDate) {

    if (inDate == null)
        return false;

    //set the format to use as a constructor argument
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    if (inDate.trim().length() != dateFormat.toPattern().length())
        return false;

    dateFormat.setLenient(false);//ww  w .ja  v  a 2  s. com

    try {
        //parse the inDate parameter
        dateFormat.parse(inDate.trim());
    } catch (ParseException pe) {
        return false;
    }
    return true;
}

From source file:net.solarnetwork.node.weather.nz.metservice.MetserviceSupport.java

/**
 * Parse a Date from an attribute value.
 * //from w ww . j  a v  a2  s .c o  m
 * <p>
 * If the date cannot be parsed, <em>null</em> will be returned.
 * </p>
 * 
 * @param key
 *        the attribute key to obtain from the {@code data} Map
 * @param data
 *        the attributes
 * @param dateFormat
 *        the date format to use to parse the date string
 * @return the parsed {@link Date} instance, or <em>null</em> if an error
 *         occurs or the specified attribute {@code key} is not available
 */
protected Date parseDateAttribute(String key, JsonNode data, SimpleDateFormat dateFormat) {
    Date result = null;
    if (data != null) {
        JsonNode node = data.get(key);
        if (node != null) {
            try {
                result = dateFormat.parse(node.asText());
            } catch (ParseException e) {
                log.debug("Error parsing date attribute [{}] value [{}] using pattern {}: {}",
                        new Object[] { key, data.get(key), dateFormat.toPattern(), e.getMessage() });
            }
        }
    }
    return result;
}

From source file:org.alfresco.web.forms.xforms.XFormsProcessor.java

/**
 * Generates html text which bootstraps the JavaScript code that will
 * call back into the XFormsBean and get the xform and build the ui.
 *///w ww  .j a v a2s  .  c  o  m
public void process(final Session session, final Writer out) throws FormProcessor.ProcessingException {
    final FacesContext fc = FacesContext.getCurrentInstance();
    //make the XFormsBean available for this session
    final XFormsBean xforms = (XFormsBean) FacesHelper.getManagedBean(fc, XFormsBean.BEAN_NAME);
    final AVMBrowseBean avmBrowseBean = (AVMBrowseBean) FacesHelper.getManagedBean(fc, AVMBrowseBean.BEAN_NAME);
    try {
        xforms.setXFormsSession((XFormsBean.XFormsSession) session);
    } catch (FormBuilderException fbe) {
        LOGGER.error(fbe);
        throw new ProcessingException(fbe);
    } catch (XFormsException xfe) {
        LOGGER.error(xfe);
        throw new ProcessingException(xfe);
    }

    final String contextPath = fc.getExternalContext().getRequestContextPath();
    final Document result = XMLUtil.newDocument();
    final String xformsUIDivId = "alfresco-xforms-ui";

    // this div is where the ui will write to
    final Element div = result.createElement("div");
    div.setAttribute("id", xformsUIDivId);
    result.appendChild(div);

    Element e = result.createElement("link");
    e.setAttribute("rel", "stylesheet");
    e.setAttribute("type", "text/css");
    e.setAttribute("href", contextPath + "/css/xforms.css");
    div.appendChild(e);

    // a script with config information and globals.
    e = result.createElement("script");
    e.setAttribute("type", "text/javascript");
    final StringBuilder js = new StringBuilder("\n");
    final String[] jsNamespacesObjects = { "alfresco", "alfresco.constants", "alfresco.xforms",
            "alfresco.xforms.constants" };
    for (final String jsNamespace : jsNamespacesObjects) {
        js.append(jsNamespace).append(" = typeof ").append(jsNamespace).append(" == 'undefined' ? {} : ")
                .append(jsNamespace).append(";\n");
    }
    js.append("alfresco.constants.DEBUG = ").append(LOGGER.isDebugEnabled()).append(";\n");
    js.append("alfresco.constants.WEBAPP_CONTEXT = '").append(JavaScriptUtils.javaScriptEscape(contextPath))
            .append("';\n");

    String avmWebApp = avmBrowseBean.getWebapp();

    // TODO - need better way to determine WCM vs ECM context
    js.append("alfresco.constants.AVM_WEBAPP_CONTEXT = '");
    if (avmWebApp != null) {
        js.append(JavaScriptUtils.javaScriptEscape(avmWebApp));
    }
    js.append("';\n");

    // TODO - need better way to determine WCM vs ECM context
    js.append("alfresco.constants.AVM_WEBAPP_URL = '");
    if (avmWebApp != null) {
        //Use preview store because when user upload image it appears in preview, not in main store.
        String storeName = AVMUtil.getCorrespondingPreviewStoreName(avmBrowseBean.getSandbox());
        if (storeName != null) {
            js.append(JavaScriptUtils.javaScriptEscape(
                    fc.getExternalContext().getRequestContextPath() + "/wcs/api/path/content/avm/"
                            + AVMUtil.buildStoreWebappPath(storeName, avmWebApp).replace(":", "")));
        }
    }

    js.append("';\n");

    js.append("alfresco.constants.AVM_WEBAPP_PREFIX = '");
    if (avmWebApp != null) {
        String storeName = AVMUtil.getCorrespondingPreviewStoreName(avmBrowseBean.getSandbox());
        if (storeName != null) {
            js.append(JavaScriptUtils.javaScriptEscape(fc.getExternalContext().getRequestContextPath()
                    + "/wcs/api/path/content/avm/" + AVMUtil.buildSandboxRootPath(storeName).replace(":", "")));
        }
    }

    js.append("';\n");
    js.append("alfresco.constants.LANGUAGE = '");
    String lang = Application.getLanguage(FacesContext.getCurrentInstance()).toString();
    // the language can be passed as "en_US" or just "en"
    if (lang.length() > 4)
        lang = lang.substring(0, lang.indexOf("_"));
    js.append(lang);
    js.append("';\n");
    js.append("alfresco.xforms.constants.XFORMS_UI_DIV_ID = '").append(xformsUIDivId).append("';\n");
    js.append("alfresco.xforms.constants.FORM_INSTANCE_DATA_NAME = '")
            .append(JavaScriptUtils.javaScriptEscape(session.getFormInstanceDataName())).append("';\n");
    SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance(DateFormat.SHORT,
            Application.getLanguage(fc));
    js.append("alfresco.xforms.constants.DATE_FORMAT = '").append(sdf.toPattern()).append("';\n");
    sdf = (SimpleDateFormat) SimpleDateFormat.getTimeInstance(DateFormat.SHORT, Application.getLanguage(fc));
    js.append("alfresco.xforms.constants.TIME_FORMAT = '").append(sdf.toPattern()).append("';\n");
    sdf = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT,
            Application.getLanguage(fc));
    js.append("alfresco.xforms.constants.DATE_TIME_FORMAT = '").append(sdf.toPattern()).append("';\n");
    for (String[] ns : JS_NAMESPACES) {
        js.append("alfresco.xforms.constants.").append(ns[0].toUpperCase()).append("_NS = '").append(ns[1])
                .append("';\n");
        js.append("alfresco.xforms.constants.").append(ns[0].toUpperCase()).append("_PREFIX = '").append(ns[2])
                .append("';\n");
    }

    final ResourceBundle bundle = Application.getBundle(FacesContext.getCurrentInstance());
    js.append("alfresco.resources = {\n");
    for (String k : BUNDLE_KEYS) {
        js.append(k).append(": '").append(JavaScriptUtils.javaScriptEscape(bundle.getString(k))).append("'")
                .append(k.equals(BUNDLE_KEYS[BUNDLE_KEYS.length - 1]) ? "\n};" : ",").append("\n");
    }

    try {
        js.append("alfresco.xforms.widgetConfig = \n")
                .append(LOGGER.isDebugEnabled() ? XFormsProcessor.widgetConfig.toString(0)
                        : XFormsProcessor.widgetConfig)
                .append("\n");
    } catch (JSONException jsone) {
        LOGGER.error(jsone);
    }
    e.appendChild(result.createTextNode(js.toString()));

    div.appendChild(e);

    // include all our scripts, order is significant
    for (final String script : JS_SCRIPTS) {
        if (script == null) {
            continue;
        }
        e = result.createElement("script");
        e.setAttribute("type", "text/javascript");
        e.setAttribute("src", contextPath + script);
        e.appendChild(result.createTextNode("\n"));
        div.appendChild(e);
    }

    // output any custom scripts
    ConfigElement config = Application.getConfigService(fc).getGlobalConfig().getConfigElement("wcm");
    if (config != null) {
        // get the custom scripts to include
        ConfigElement xformsScriptsConfig = config.getChild("xforms-scripts");
        if (xformsScriptsConfig != null) {
            StringTokenizer t = new StringTokenizer(xformsScriptsConfig.getValue().trim(), ", ");
            while (t.hasMoreTokens()) {
                e = result.createElement("script");
                e.setAttribute("type", "text/javascript");
                e.setAttribute("src", contextPath + t.nextToken());
                e.appendChild(result.createTextNode("\n"));
                div.appendChild(e);
            }
        }
    }

    XMLUtil.print(result, out);
}

From source file:edu.ku.brc.af.prefs.AppPrefsCache.java

/**
 * Creates or gets the pref node, creates an entry and then hooks it up as a listener.
 * The current value of the SimpleDateFormat because the default.
 * @param simpleFormat the SimpleDateFormat object 
 * @param section the section or category of the pref
 * @param pref the pref's name/*from  w w w  .j  a v a2s. co m*/
 * @param attrName the actual attribute
 */
public void registerInternal(final SimpleDateFormat simpleFormat, final String section, final String pref,
        final String attrName) {
    checkName(section, pref, attrName);

    String fullName = makeKey(section, pref, attrName);
    if (hash.get(fullName) == null) {
        String defValue = simpleFormat.toPattern();
        String prefVal = checkForPref(fullName, defValue);

        //-------------------------------------------------------------------------------
        // This corrects the formatter when it has a two digit year (Bug 7555)
        // still have not found out what is causing the problem.
        //-------------------------------------------------------------------------------
        if (prefVal.length() == 8 && StringUtils.countMatches(prefVal, "yyyy") == 0) {
            prefVal = StringUtils.replace(prefVal, "yy", "yyyy");
        }

        simpleFormat.applyPattern(prefVal);
        DateFormatCacheEntry dateEntry = new DateFormatCacheEntry(simpleFormat, fullName, prefVal, defValue);
        getPref().addChangeListener(fullName, dateEntry);
        hash.put(fullName, dateEntry);
    }

}