Example usage for java.text SimpleDateFormat applyPattern

List of usage examples for java.text SimpleDateFormat applyPattern

Introduction

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

Prototype

public void applyPattern(String pattern) 

Source Link

Document

Applies the given pattern string to this date format.

Usage

From source file:com.appeligo.search.actions.account.BaseAccountAction.java

protected void extractBirthMonthYear(User user) {
    if (user != null && user.getBirthMonthYear() != null) {
        java.util.Date date = new java.util.Date(user.getBirthMonthYear().getTime());
        SimpleDateFormat format = new SimpleDateFormat();
        format.applyPattern("yyyy");
        birthYear = format.format(date);
        format.applyPattern("MMM");
        birthMonth = format.format(date).toUpperCase();
    }// w  w  w .  ja v a2 s. c om
}

From source file:nl.b3p.viewer.admin.stripes.ServiceUsageMatrixActionBean.java

@DefaultHandler
public Resolution view()
        throws JSONException, TransformerConfigurationException, TransformerException, Exception {
    List<Application> applications = Stripersist.getEntityManager()
            .createQuery("FROM Application order by name,version").getResultList();
    JSONArray jsonApps = new JSONArray();
    for (Application app : applications) {
        JSONObject json = new JSONObject(app.toJSON(this.context.getRequest(), true, true));
        jsonApps.put(json);//w w  w  . j  ava2s. c o  m
    }
    //add the featureSources to the JSON.
    List<FeatureSource> featureSources;
    if (this.featureSource == null) {
        featureSources = Stripersist.getEntityManager().createQuery("FROM FeatureSource").getResultList();
    } else {
        featureSources = new ArrayList<FeatureSource>();
        featureSources.add(this.featureSource);
    }
    JSONArray featureSourcesJson = new JSONArray();
    for (FeatureSource fs : featureSources) {
        JSONObject fsJson = fs.toJSONObject();
        featureSourcesJson.put(fsJson);

        JSONObject featuretypesRoot = new JSONObject();
        JSONArray ftJsonArray = new JSONArray();
        featuretypesRoot.put("featureType", ftJsonArray);
        fsJson.put("featuretypes", featuretypesRoot);

        List<SimpleFeatureType> featureTypes = fs.getFeatureTypes();
        for (SimpleFeatureType sft : featureTypes) {
            JSONObject ftJson = new JSONObject();
            ftJson.put("id", sft.getId());
            ftJson.put("name", sft.getTypeName());
            ftJson.put("description", sft.getDescription());
            ftJsonArray.put(ftJson);
        }
    }
    //format a json for the xml output.
    JSONObject fs = new JSONObject();
    fs.put("featureSource", featureSourcesJson);

    JSONObject appl = new JSONObject();
    appl.put("application", jsonApps);
    //make root elements for applicatons and featuresources
    JSONObject firstChild = new JSONObject();
    firstChild.put("applications", appl);
    firstChild.put("featureSources", fs);

    JSONObject root = new JSONObject();
    root.put("root", firstChild);

    //make xml
    String rawXml = org.json.XML.toString(root);

    this.xml = transformXml(rawXml);
    Date nowDate = new Date(System.currentTimeMillis());
    SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
    sdf.applyPattern("HH-mm_dd-MM-yyyy");
    String now = sdf.format(nowDate);
    final String fileName = "UsageMatrix_" + now;
    if (output_format != null || "XLS".equalsIgnoreCase(output_format)) {
        final XSSFWorkbook workbook = createWorkBook(this.xml);
        return new StreamingResolution("application/vnd.ms-excel") {
            public void stream(final HttpServletResponse response) {
                try {
                    workbook.write(response.getOutputStream());
                } catch (IOException ioe) {
                    log.error("Error while writing workbook", ioe);
                }
            }
        }.setAttachment(true).setFilename(fileName + ".xls");
    }
    return new ForwardResolution(JSP);
}

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

/**
 * Description of the Method//w  w  w .j a  v  a2 s  . c o 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.emr.utilities.CSVLoader.java

/**
 * Method to format a String to a date// w  w  w. j av a2  s  .c om
 * @param oldString {@link String} the string to be formatted
 * @return {@link java.sql.Date} The date object
 */
private java.sql.Date formatDate(String oldString) {
    java.sql.Date newDateString = null;
    try {
        final String OLD_FORMAT = "dd-MMM-yyyy";
        final String NEW_FORMAT = "dd/MM/yyyy HH:mm:ss";

        SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
        Date d = sdf.parse(oldString);
        sdf.applyPattern(NEW_FORMAT);
        newDateString = new java.sql.Date(d.getTime());
    } catch (ParseException ex) {
        //Logger.getLogger(CSVLoader.class.getName()).log(Level.WARNING, null, ex);

    }
    return newDateString;
}

From source file:org.jamwiki.parser.jflex.MagicWordUtil.java

/**
 * Process metadata magic words.//w w w  .j a v a2  s.  co m
 */
private static String processMagicWordMetadata(ParserInput parserInput, String name)
        throws DataAccessException {
    SimpleDateFormat formatter = new SimpleDateFormat();
    TimeZone utc = TimeZone.getTimeZone("GMT+00");
    Topic topic = WikiBase.getDataHandler().lookupTopic(parserInput.getVirtualWiki(),
            parserInput.getTopicName(), false);
    TopicVersion topicVersion = null;
    Date revision = null;
    // null check needed for the test data handler, which does not implement topic versions
    if (topic != null && topic.getCurrentVersionId() != null) {
        topicVersion = WikiBase.getDataHandler().lookupTopicVersion(topic.getCurrentVersionId());
        revision = topicVersion.getEditDate();
    }
    formatter.setTimeZone(utc);
    if (name.equals(MAGIC_REVISION_DAY)) {
        if (revision == null) {
            return "";
        }
        formatter.applyPattern("d");
        return formatter.format(revision);
    }
    if (name.equals(MAGIC_REVISION_DAY2)) {
        if (revision == null) {
            return "";
        }
        formatter.applyPattern("dd");
        return formatter.format(revision);
    }
    if (name.equals(MAGIC_REVISION_MONTH)) {
        if (revision == null) {
            return "";
        }
        formatter.applyPattern("M");
        return formatter.format(revision);
    }
    if (name.equals(MAGIC_REVISION_MONTH1)) {
        if (revision == null) {
            return "";
        }
        formatter.applyPattern("MM");
        return formatter.format(revision);
    }
    if (name.equals(MAGIC_REVISION_YEAR)) {
        if (revision == null) {
            return "";
        }
        formatter.applyPattern("yyyy");
        return formatter.format(revision);
    }
    if (name.equals(MAGIC_REVISION_TIMESTAMP)) {
        if (revision == null) {
            return "";
        }
        formatter.applyPattern("yyyyMMddHHmmss");
        return formatter.format(revision);
    }
    if (name.equals(MAGIC_REVISION_USER)) {
        if (topicVersion == null) {
            return "";
        }
        WikiUser wikiUser = (topicVersion.getAuthorId() != null)
                ? WikiBase.getDataHandler().lookupWikiUser(topicVersion.getAuthorId())
                : null;
        return (wikiUser != null) ? wikiUser.getUsername() : topicVersion.getAuthorDisplay();
    }
    if (name.equals(MAGIC_REVISION_ID)) {
        return (topicVersion == null) ? "" : Integer.toString(topicVersion.getTopicVersionId());
    }
    if (name.equals(MAGIC_SITE_NAME)) {
        VirtualWiki virtualWiki = WikiBase.getDataHandler().lookupVirtualWiki(parserInput.getVirtualWiki());
        return virtualWiki.getSiteName();
    }
    if (name.equals(MAGIC_SERVER)) {
        return Environment.getValue(Environment.PROP_SERVER_URL);
    }
    if (name.equals(MAGIC_SERVER_NAME)) {
        // strip the opening "http://" if there is one
        String result = Environment.getValue(Environment.PROP_SERVER_URL);
        int pos = result.indexOf("://");
        return (pos == -1) ? result : result.substring(pos + "://".length());
    }
    return name;
}

From source file:net.solarnetwork.web.support.SimpleXmlView.java

/**
 * Create a {@link SimpleDateFormat} and cache on the {@link #SDF}
 * ThreadLocal to re-use for all dates within a single response.
 * //from   www. j ava 2  s  .  c  o  m
 * @param model
 *        the model, to look for a TimeZone to format the dates in
 */
private Map<String, Object> setupDateFormat(Map<String, Object> model) {
    TimeZone tz = TimeZone.getTimeZone("GMT");
    Map<String, Object> result = new LinkedHashMap<String, Object>();
    for (Map.Entry<String, Object> me : model.entrySet()) {
        Object o = me.getValue();
        if (useModelTimeZoneForDates && o instanceof TimeZone) {
            tz = (TimeZone) o;
        } else if (modelKey != null) {
            if (modelKey.equals(me.getKey())) {
                result.put(modelKey, o);
            }
        } else { //if ( !(o instanceof BindingResult) ) {
            result.put(me.getKey(), o);
        }
    }
    SimpleDateFormat sdf = new SimpleDateFormat();
    if (tz.getRawOffset() == 0) {
        sdf.applyPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    } else {
        sdf.applyPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    }
    sdf.setTimeZone(tz);
    if (logger.isTraceEnabled()) {
        logger.trace("TZ offset " + tz.getRawOffset());
    }
    SDF.set(sdf);
    return result;
}

From source file:org.sipana.server.web.sip.SIPSessionController.java

private String getDateString(long dateInMillis) {
    SimpleDateFormat dateFormat = new SimpleDateFormat();
    Calendar now = Calendar.getInstance();
    Calendar date = Calendar.getInstance();
    date.setTimeInMillis(dateInMillis);/*from www  . j  ava2 s. co  m*/

    if (now.get(Calendar.DAY_OF_MONTH) == date.get(Calendar.DAY_OF_MONTH)) {
        dateFormat.applyPattern("HH:mm:ss,S");
        return dateFormat.format(date.getTime());
    } else {
        dateFormat.applyPattern("yyyy-MM-dd HH:mm:ss,S");
        return dateFormat.format(date.getTime());
    }
}

From source file:org.betaconceptframework.astroboa.portal.utility.CalendarUtils.java

public String convertDateToString(Date date, String dateFormatPattern) {
    SimpleDateFormat dateFormat = (SimpleDateFormat) DateFormat.getDateInstance();
    dateFormat.setLenient(false); // be strict in the formatting
    // apply accepted pattern
    dateFormat.applyPattern(dateFormatPattern);

    return dateFormat.format(date);
}

From source file:com.funambol.exchange.util.DateTools.java

/**
 * Converts a all day Funambol date to an allday ExchangeDate
 * //  w  w  w  . j  a  v  a2s  .c  o m
 * @param date
 * @param timezone
 * @param isAStartDate
 * @return
 * @throws com.funambol.exchange.xml.XmlParseException
 */
public static String convertDayToWebDavDate(String date, String timezone) throws XmlParseException {
    SimpleDateFormat formatter;
    Date dt;
    String wedDavDate, value;
    String timePart = null;

    if (date != null && date.length() > 0) {
        if (date.length() != 8) {
            date = date.replaceAll("-", "");
        }
        timePart = "T000000Z";
        value = date + timePart;

        formatter = new SimpleDateFormat(DATE_FORMAT_PDI);

        try {
            formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
            dt = formatter.parse(value);
            long time = dt.getTime();
            long offset = TimeZone.getTimeZone(timezone).getOffset(time);
            dt = new Date(time - offset);
        } catch (ParseException e) {
            throw new XmlParseException("Error converting date", e);
        }
        formatter.applyPattern(DATE_FORMAT_WEBDAV);
        wedDavDate = formatter.format(dt);

    } else {
        wedDavDate = null;
    }

    return wedDavDate;
}

From source file:org.springframework.social.weibo.api.impl.json.TrendsDeserializer.java

@Override
public SortedSet<Trends> deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    SimpleDateFormat dateFormat = new SimpleDateFormat();
    TreeSet<Trends> result = new TreeSet<Trends>(comparator);
    TreeNode treeNode = jp.readValueAsTree();

    Iterator<String> fieldNames = treeNode.fieldNames();

    while (fieldNames.hasNext()) {
        Trends trends = new Trends();
        try {/*  www.  j  a v a  2 s  .  c om*/
            String filedName = fieldNames.next();
            dateFormat.applyPattern(retrieveDateFormatPattern(filedName));
            trends.setDate(dateFormat.parse(filedName));
            TreeNode trendsNode = treeNode.get(filedName);
            if (trendsNode.isArray()) {
                for (int i = 0; i < trendsNode.size(); i++) {
                    JsonParser nodeParser = trendsNode.get(i).traverse();
                    nodeParser.setCodec(jp.getCodec());
                    Trend readValueAs = nodeParser.readValueAs(Trend.class);
                    trends.getTrends().add(readValueAs);
                }
            }
            result.add(trends);
        } catch (ParseException e) {
            logger.warn("Unable to parse date", e);
        }
    }

    return result;
}