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:org.jumpmind.util.FormatUtils.java

public static Date parseDate(String str, String[] parsePatterns, TimeZone timeZone) {
    if (str == null || parsePatterns == null) {
        throw new IllegalArgumentException("Date and Patterns must not be null");
    }//from   w w  w.  j a  v a 2  s  . c om

    SimpleDateFormat parser = null;
    ParsePosition pos = new ParsePosition(0);
    for (int i = 0; i < parsePatterns.length; i++) {
        if (i == 0) {
            parser = new SimpleDateFormat(parsePatterns[0]);
            if (timeZone != null) {
                parser.setTimeZone(timeZone);
            }
        } else {
            parser.applyPattern(parsePatterns[i]);
        }
        pos.setIndex(0);
        Date date = parser.parse(str, pos);
        if (date != null && pos.getIndex() == str.length()) {
            return date;
        }
    }

    try {
        Date date = new Date(Long.parseLong(str));
        return date;
    } catch (NumberFormatException e) {

    }

    throw new ParseException("Unable to parse the date: " + str);
}

From source file:org.apache.solr.common.util.DateUtil.java

/**
 * Slightly modified from org.apache.commons.httpclient.util.DateUtil.parseDate
 * <p/>/*  w  w w .  ja  v a2  s.c  om*/
 * Parses the date value using the given date formats.
 *
 * @param dateValue   the date value to parse
 * @param dateFormats the date formats to use
 * @param startDate   During parsing, two digit years will be placed in the range
 *                    <code>startDate</code> to <code>startDate + 100 years</code>. This value may
 *                    be <code>null</code>. When <code>null</code> is given as a parameter, year
 *                    <code>2000</code> will be used.
 * @return the parsed date
 * @throws ParseException if none of the dataFormats could parse the dateValue
 */
public static Date parseDate(String dateValue, Collection<String> dateFormats, Date startDate)
        throws ParseException {

    if (dateValue == null) {
        throw new IllegalArgumentException("dateValue is null");
    }
    if (dateFormats == null) {
        dateFormats = DEFAULT_HTTP_CLIENT_PATTERNS;
    }
    if (startDate == null) {
        startDate = DEFAULT_TWO_DIGIT_YEAR_START;
    }
    // trim single quotes around date if present
    // see issue #5279
    if (dateValue.length() > 1 && dateValue.startsWith("'") && dateValue.endsWith("'")) {
        dateValue = dateValue.substring(1, dateValue.length() - 1);
    }

    SimpleDateFormat dateParser = null;
    Iterator formatIter = dateFormats.iterator();

    while (formatIter.hasNext()) {
        String format = (String) formatIter.next();
        if (dateParser == null) {
            dateParser = new SimpleDateFormat(format, Locale.US);
            dateParser.setTimeZone(GMT);
            dateParser.set2DigitYearStart(startDate);
        } else {
            dateParser.applyPattern(format);
        }
        try {
            return dateParser.parse(dateValue);
        } catch (ParseException pe) {
            // ignore this exception, we will try the next format
        }
    }

    // we were unable to parse the date
    throw new ParseException("Unable to parse the date " + dateValue, 0);
}

From source file:org.posterita.businesslogic.performanceanalysis.CustomPOSReportManager.java

public static TimeSeriesChart generateTimeSeriesChart(Properties ctx, String title, String subtitle,
        int account_id, Timestamp fromDate, Timestamp toDate, String salesGroup, String priceQtyFilter)
        throws OperationException {
    TimeSeriesChart timeSeriesChart = new TimeSeriesChart();
    timeSeriesChart.setTitle(title);/*ww w  .j  a  v a  2s  .  c o m*/
    timeSeriesChart.setSubtitle(subtitle);
    timeSeriesChart.setShowShapes(true);
    //timeSeriesChart.getDataSetFromSQL(timeSeriesChartSQL);

    String timeSeriesChartSQL = SalesAnalysisReportManager.getTimeSeriesDataSetSQL(ctx, account_id, fromDate,
            toDate, salesGroup);
    ArrayList<Object[]> list = ReportManager.getReportData(ctx, timeSeriesChartSQL, false);

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    TimeSeries series = null;
    String yLabel = null;

    String seriesName = null;
    String date = null;
    BigDecimal price = null;
    String[] s = null;
    int day, month, year;

    for (Object[] data : list) {
        seriesName = (String) data[0];
        date = (String) data[1];
        price = (BigDecimal) data[2];
        s = date.split("-");

        if (s.length != 3)
            throw new OperationException("Unable to generate timeseries. "
                    + "Cause:Invalid date format, the date returned should have the following format 'DD-MM-YYYY'");

        SimpleDateFormat sdf = new SimpleDateFormat();
        Calendar cal = Calendar.getInstance();
        Date d = null;

        try {
            sdf.applyPattern("dd-MM-yyyy");
            d = sdf.parse(date);
        } catch (ParseException e1) {
            try {
                sdf.applyPattern("dd-MMM-yyyy");
                d = sdf.parse(date);
            } catch (ParseException e) {
                throw new OperationException("Unable to generate timeseries. "
                        + "Cause:Invalid date format, the date returned should have one of the following formats 'DD-MM-YYYY' or 'DD-MMM-YYYY'",
                        e);
            }
        }

        cal.setTime(d);

        day = cal.get(Calendar.DATE);
        month = cal.get(Calendar.MONTH) + 1;
        year = cal.get(Calendar.YEAR);

        series = dataset.getSeries(seriesName);

        if (series == null) {
            series = new TimeSeries(seriesName, Day.class);
            series.add(new Day(day, month, year), price);

            dataset.addSeries(series);
        } else {
            series.add(new Day(day, month, year), price);
        } //if   

    } //for

    if (priceQtyFilter.equalsIgnoreCase(Constants.PRICE)) {
        //against price
        String currency = POSTerminalManager.getDefaultSalesCurrency(ctx).getCurSymbol();
        yLabel = "Value (" + currency + ")";
    } else {
        yLabel = "Quantity";
    }

    timeSeriesChart.setYLabel(yLabel);
    timeSeriesChart.setDataset(dataset);
    XYPlot plot = (XYPlot) timeSeriesChart.getChart().getPlot();
    DateAxis axis = (DateAxis) plot.getDomainAxis();

    SimpleDateFormat sdf = new SimpleDateFormat(TimestampConvertor.DEFAULT_DATE_PATTERN1);

    axis.setRange(fromDate, toDate);
    //axis.setTickUnit(new DateTickUnit(DateTickUnit.MONTH,1,new SimpleDateFormat("MMM-yyyy")));        
    timeSeriesChart.getChart().setBackgroundPaint(Color.white);

    return timeSeriesChart;
}

From source file:org.tsm.concharto.util.TimeRangeFormat.java

/**
 * Utility for checking precision of user entered dates 
 * @param text date string/* w w  w .j ava  2s  . com*/
 * @param patterns array of patterns (see SimpleDateFormat)
 * @return true if the date is parseable using the provided pattern
 */
private static boolean isParseable(String text, String[] patterns) {
    SimpleDateFormat sdf = new SimpleDateFormat();
    sdf.setLenient(false);
    for (String pattern : patterns) {
        try {
            sdf.applyPattern(pattern);
            sdf.parse(text);
            return true;
        } catch (ParseException e) {
            //no action
        }
    }
    return false;
}

From source file:com.cloudlbs.core.utils.DateUtil.java

/**
 * Slightly modified from// w  w  w .  j av  a 2 s. c om
 * org.apache.commons.httpclient.util.DateUtil.parseDate
 * <p/>
 * Parses the date value using the given date formats.
 * 
 * @param dateValue
 *            the date value to parse
 * @param dateFormats
 *            the date formats to use
 * @param startDate
 *            During parsing, two digit years will be placed in the range
 *            <code>startDate</code> to <code>startDate + 100 years</code>.
 *            This value may be <code>null</code>. When <code>null</code> is
 *            given as a parameter, year <code>2000</code> will be used.
 * @return the parsed date
 * @throws ParseException
 *             if none of the dataFormats could parse the dateValue
 */
public static Date parseDate(String dateValue, Collection<String> dateFormats, Date startDate)
        throws ParseException {

    if (dateValue == null) {
        throw new IllegalArgumentException("dateValue is null");
    }
    if (dateFormats == null) {
        dateFormats = DEFAULT_HTTP_CLIENT_PATTERNS;
    }
    if (startDate == null) {
        startDate = DEFAULT_TWO_DIGIT_YEAR_START;
    }
    // trim single quotes around date if present
    // see issue #5279
    if (dateValue.length() > 1 && dateValue.startsWith("'") && dateValue.endsWith("'")) {
        dateValue = dateValue.substring(1, dateValue.length() - 1);
    }

    SimpleDateFormat dateParser = null;
    Iterator<String> formatIter = dateFormats.iterator();

    while (formatIter.hasNext()) {
        String format = (String) formatIter.next();
        if (dateParser == null) {
            dateParser = new SimpleDateFormat(format, Locale.US);
            dateParser.setTimeZone(GMT);
            dateParser.set2DigitYearStart(startDate);
        } else {
            dateParser.applyPattern(format);
        }
        try {
            return dateParser.parse(dateValue);
        } catch (ParseException pe) {
            // ignore this exception, we will try the next format
        }
    }

    // we were unable to parse the date
    throw new ParseException("Unable to parse the date " + dateValue, 0);
}

From source file:com.camel.framework.utils.DateUtils.java

/**
 * ?// w ww .  j  av  a 2 s . co m
 * 
 * @param strDate
 * @return 
 */
public static String getStandardDateString(String strDate) {

    SimpleDateFormat objFormat = new SimpleDateFormat(STANDARD);

    Date objDate = null;

    for (int i = 0; i < 2; i++) {
        try {
            objDate = objFormat.parse(strDate);

            objFormat.applyPattern(STANDARD);

        } catch (ParseException e) {
            objFormat.applyPattern(DATE);
        }
    }

    if (null != objDate) {
        return objFormat.format(objDate);
    }

    return null;
}

From source file:com.glaf.core.util.DateUtils.java

public static Date parseDate(String str, String[] parsePatterns) {
    if (str == null || parsePatterns == null) {
        throw new IllegalArgumentException("Date and Patterns must not be null");
    }/*from ww  w . j ava 2 s.c om*/
    SimpleDateFormat parser = null;
    ParsePosition pos = new ParsePosition(0);
    for (int i = 0; i < parsePatterns.length; i++) {
        if (i == 0) {
            parser = new SimpleDateFormat(parsePatterns[0]);
        } else {
            parser.applyPattern(parsePatterns[i]);
        }
        pos.setIndex(0);
        Date date = parser.parse(str, pos);
        if (date != null && pos.getIndex() == str.length()) {
            return date;
        }
    }
    throw new RuntimeException("Unable to parse the date: " + str);
}

From source file:org.opendatakit.briefcase.util.WebUtils.java

private static final Date parseDateSubset(String value, String[] parsePatterns, Locale l, TimeZone tz) {
    // borrowed from apache.commons.lang.DateUtils...
    Date d = null;//  ww  w.  j a v  a  2s .  c o m
    SimpleDateFormat parser = null;
    ParsePosition pos = new ParsePosition(0);
    for (int i = 0; i < parsePatterns.length; i++) {
        if (i == 0) {
            if (l == null) {
                parser = new SimpleDateFormat(parsePatterns[0]);
            } else {
                parser = new SimpleDateFormat(parsePatterns[0], l);
            }
        } else {
            parser.applyPattern(parsePatterns[i]);
        }
        parser.setTimeZone(tz); // enforce UTC for formats without timezones
        pos.setIndex(0);
        d = parser.parse(value, pos);
        if (d != null && pos.getIndex() == value.length()) {
            return d;
        }
    }
    return d;
}

From source file:org.pentaho.di.core.util.StringUtil.java

public static Date str2dat(String arg0, String arg1, String val) throws KettleValueException {
    SimpleDateFormat df = new SimpleDateFormat();

    DateFormatSymbols dfs = new DateFormatSymbols();
    if (arg1 != null) {
        dfs.setLocalPatternChars(arg1);/*  ww w  .  j a  v a2s. c o  m*/
    }
    if (arg0 != null) {
        df.applyPattern(arg0);
    }

    try {
        return df.parse(val);
    } catch (Exception e) {
        throw new KettleValueException("TO_DATE Couldn't convert String to Date " + e.toString());
    }
}

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

/**
 * Process date & time magic words./*from  w  w  w. j  a  va2  s . c om*/
 */
private static String processMagicWordDateTime(ParserInput parserInput, String name)
        throws DataAccessException {
    SimpleDateFormat formatter = new SimpleDateFormat();
    Date current = new Date(System.currentTimeMillis());
    // local date values
    if (name.equals(MAGIC_LOCAL_DAY)) {
        formatter.applyPattern("d");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_LOCAL_DAY2)) {
        formatter.applyPattern("dd");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_LOCAL_DAY_NAME)) {
        formatter.applyPattern("EEEE");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_LOCAL_DAY_OF_WEEK)) {
        formatter.applyPattern("F");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_LOCAL_MONTH)) {
        formatter.applyPattern("MM");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_LOCAL_MONTH_ABBR)) {
        formatter.applyPattern("MMM");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_LOCAL_MONTH_NAME)) {
        formatter.applyPattern("MMMM");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_LOCAL_TIME)) {
        formatter.applyPattern("HH:mm");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_LOCAL_HOUR)) {
        formatter.applyPattern("HH");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_LOCAL_WEEK)) {
        formatter.applyPattern("w");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_LOCAL_YEAR)) {
        formatter.applyPattern("yyyy");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_LOCAL_TIMESTAMP)) {
        formatter.applyPattern("yyyyMMddHHmmss");
        return formatter.format(current);
    }
    // current date values
    TimeZone utc = TimeZone.getTimeZone("GMT+00");
    formatter.setTimeZone(utc);
    if (name.equals(MAGIC_CURRENT_DAY)) {
        formatter.applyPattern("d");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_CURRENT_DAY2)) {
        formatter.applyPattern("dd");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_CURRENT_DAY_NAME)) {
        formatter.applyPattern("EEEE");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_CURRENT_DAY_OF_WEEK)) {
        formatter.applyPattern("F");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_CURRENT_MONTH)) {
        formatter.applyPattern("MM");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_CURRENT_MONTH_ABBR)) {
        formatter.applyPattern("MMM");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_CURRENT_MONTH_NAME)) {
        formatter.applyPattern("MMMM");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_CURRENT_TIME)) {
        formatter.applyPattern("HH:mm");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_CURRENT_HOUR)) {
        formatter.applyPattern("HH");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_CURRENT_WEEK)) {
        formatter.applyPattern("w");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_CURRENT_YEAR)) {
        formatter.applyPattern("yyyy");
        return formatter.format(current);
    }
    if (name.equals(MAGIC_CURRENT_TIMESTAMP)) {
        formatter.applyPattern("yyyyMMddHHmmss");
        return formatter.format(current);
    }
    return name;
}