Example usage for java.text DateFormat parse

List of usage examples for java.text DateFormat parse

Introduction

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

Prototype

public Date parse(String source) throws ParseException 

Source Link

Document

Parses text from the beginning of the given string to produce a date.

Usage

From source file:com.streamsets.pipeline.lib.parser.excel.TestWorkbookParser.java

@Test
public void testARealSpreadsheetWithMultipleSheets()
        throws IOException, InvalidFormatException, DataParserException, ParseException {
    Workbook workbook = createWorkbook("/excel/TestRealSheet.xlsx");

    WorkbookParser parser = new WorkbookParser(settingsWithHeader, getContext(), workbook, "Orders::0");

    // column header prefix, row value multiplier
    List<Pair<String, Integer>> sheetParameters = Arrays.asList(Pair.of("column", 1), Pair.of("header", 10));

    // TEST 1 - verify first non-header record of first sheet
    LinkedHashMap<String, Field> Sheet1Headers = new LinkedHashMap<>();
    String[] Sheet1HdrList = { "Row ID", "Order ID", "Order Date", "Ship Date", "Ship Mode", "Customer ID",
            "Customer Name", "Segment", "Country", "City", "State", "Postal Code", "Region", "Product ID",
            "Category", "Sub-Category", "Product Name", "Sales", "Quantity", "Discount", "Profit" };
    for (int i = 0; i < Sheet1HdrList.length; i++) {
        Sheet1Headers.put(Sheet1HdrList[i], Field.create(Sheet1HdrList[i]));
    }//from   ww  w  . ja va2  s.  c om
    LinkedHashMap<String, Field> row1Expected = new LinkedHashMap<>();
    DateFormat df = new SimpleDateFormat("MM-dd-yyyy");

    row1Expected.put("Row ID", Field.create(new BigDecimal(1.0)));
    row1Expected.put("Order ID", Field.create("CA-2016-152156"));
    row1Expected.put("Order Date", Field.createDate(df.parse("11-08-2016")));
    row1Expected.put("Ship Date", Field.createDate(df.parse("11-11-2016")));
    row1Expected.put("Ship Mode", Field.create("Second Class"));
    row1Expected.put("Customer ID", Field.create("CG-12520"));
    row1Expected.put("Customer Name", Field.create("Claire Gute"));
    row1Expected.put("Segment", Field.create("Consumer"));
    row1Expected.put("Country", Field.create("United States"));
    row1Expected.put("City", Field.create("Henderson"));
    row1Expected.put("State", Field.create("Kentucky"));
    row1Expected.put("Postal Code", Field.create(new BigDecimal("42420")));
    row1Expected.put("Region", Field.create("South"));
    row1Expected.put("Product ID", Field.create("FUR-BO-10001798"));
    row1Expected.put("Category", Field.create("Furniture"));
    row1Expected.put("Sub-Category", Field.create("Bookcases"));
    row1Expected.put("Product Name", Field.create("Bush Somerset Collection Bookcase"));
    row1Expected.put("Sales", Field.create(new BigDecimal("261.96")));
    row1Expected.put("Quantity", Field.create(new BigDecimal("2")));
    row1Expected.put("Discount", Field.create(new BigDecimal("0")));
    row1Expected.put("Profit", Field.create(new BigDecimal("41.9136")));

    Record parsedRow = parser.parse();
    Field expectedRow = Field.createListMap(row1Expected);
    assertEquals("Parsed value for sheet Orders, row 1 did not match expected value", expectedRow,
            parsedRow.get());

    // TEST 2 - Verify first non-header record on second sheet
    LinkedHashMap<String, Field> sheet2Expected = new LinkedHashMap<>();
    sheet2Expected.put("Returned", Field.create("Yes"));
    sheet2Expected.put("Order ID", Field.create("CA-2017-153822"));
    expectedRow = Field.createListMap(sheet2Expected);
    parser = new WorkbookParser(settingsWithHeader, getContext(), workbook, "Returns::0");
    parsedRow = parser.parse();
    assertEquals("Parsed value for sheet Returns, row 1 did not match expected value", expectedRow,
            parsedRow.get());

    // TEST 3 - Verify total rows processed is what is in the sheet (minus header rows)
    parser = new WorkbookParser(settingsWithHeader, getContext(), workbook, "Orders::0");
    int numRows = 0;
    while (parser.getOffset() != "-1") {
        parser.parse();
        ++numRows;
    }
    --numRows; // remove last increment because that round would have generated EOF
    assertEquals("Total record count mismatch", 10294, numRows);

}

From source file:gov.nasa.ensemble.common.io.RemotableFile.java

private void setModifiedTime(HttpGet get) {
    try {/*  w ww.  ja va  2  s . c o  m*/
        String mod = get.getLastHeader(HttpHeaders.LAST_MODIFIED).getValue();
        //DateFormat does not seem thread safe, so we need a new instance each time
        DateFormat df = new SimpleDateFormat(DATE_FORMAT_STR);
        long resp_mod_time = df.parse(mod).getTime();
        if (resp_mod_time > 0) {
            localFile.setLastModified(resp_mod_time);
        } else {
            //usually caused by unsafe thread use of DateFormat
            trace.error("Negative Time. ");
        }
    } catch (ParseException e) {
        trace.error("Error parsing date from the http response: " + e.toString());
    }
}

From source file:com.registryKit.client.clientDAO.java

/**
 * The 'updateClientFields' function will update the fields from the client form
 * //from w  w  w . j  a  va  2  s.c o  m
 * @param clientId The id of the client being updated
 * @param tableName The table to be updated
 * @param tableCol  The column to update
 * @param tableValue  The new value to save into the column
 */
public void updateClientFields(Integer clientId, String tableName, String tableCol, String fieldValue,
        String currFieldValue, Integer fieldId, Integer fieldType, Integer systemUserId) throws Exception {

    String sqlQuery;

    /* Check to see if the field is a date field */
    if (fieldType == 6) {
        DateFormat format = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);
        Date date = format.parse(fieldValue);
        Timestamp timestamp = new Timestamp(date.getTime());

        sqlQuery = "update " + tableName + " set " + tableCol + " = '" + timestamp
                + "' where programpatientId = " + clientId;

    } else {
        sqlQuery = "update " + tableName + " set " + tableCol + " = '" + fieldValue
                + "' where programpatientId = " + clientId;
    }

    Query query = sessionFactory.getCurrentSession().createSQLQuery(sqlQuery);
    query.executeUpdate();

    /* Insert the modified entry */
    if (!currFieldValue.equals(fieldValue)) {
        modifiedFields modifiedField = new modifiedFields();
        modifiedField.setFieldId(fieldId);
        modifiedField.setProgramPatientId(clientId);
        modifiedField.setSystemUserId(systemUserId);
        modifiedField.setOldFieldValue(currFieldValue);
        modifiedField.setNewFieldValue(fieldValue);

        sessionFactory.getCurrentSession().save(modifiedField);
    }
}

From source file:com.charts.SixMonthChart.java

protected OHLCDataItem[] getData(YStockQuote currentStock) throws ParseException {
    ArrayList<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>();
    DateFormat df;
    if (currentStock instanceof Index)
        df = new SimpleDateFormat("y-MM-dd");
    else/*w ww  .j ava2  s  .c  om*/
        df = new SimpleDateFormat("d-MM-yy");
    String sixMonthDate = df.format(DayRange.six_month);
    ArrayList<String> historicalData = currentStock.get_historical_data();
    int length = historicalData.size();
    for (int i = 1; i < length; i++) {

        String[] data = historicalData.get(i).split(",");

        Date date = df.parse(data[0]);
        double open = Double.parseDouble(data[1]);
        double high = Double.parseDouble(data[2]);
        double low = Double.parseDouble(data[3]);
        double close = Double.parseDouble(data[4]);
        this.close.add(new Day(date), close);
        double volume;
        try {
            volume = Double.parseDouble(data[5]);
        } catch (NumberFormatException nfe) {
            volume = 0;
        }
        if (data[0].equals(sixMonthDate)) {
            break;
        }

        OHLCDataItem item = new OHLCDataItem(date, open, high, low, close, volume);
        dataItems.add(item);
    }
    Collections.reverse(dataItems);

    OHLCDataItem[] OHLCData = dataItems.toArray(new OHLCDataItem[dataItems.size()]);
    return OHLCData;
}

From source file:com.charts.ThreeMonthChart.java

protected OHLCDataItem[] getData(YStockQuote currentStock) throws ParseException {
    ArrayList<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>();
    DateFormat df;
    if (currentStock instanceof Index)
        df = new SimpleDateFormat("y-MM-dd");
    else//  w  w w.  j  a v  a  2 s  .co  m
        df = new SimpleDateFormat("d-MM-yy");
    String threeMonthDate = df.format(DayRange.three_month);
    ArrayList<String> historicalData = currentStock.get_historical_data();
    int length = historicalData.size();
    for (int i = 1; i < length; i++) {

        String[] data = historicalData.get(i).split(",");

        Date date = df.parse(data[0]);
        double open = Double.parseDouble(data[1]);
        double high = Double.parseDouble(data[2]);
        double low = Double.parseDouble(data[3]);
        double close = Double.parseDouble(data[4]);
        this.close.add(new Day(date), close);

        double volume;
        try {
            volume = Double.parseDouble(data[5]);
        } catch (NumberFormatException nfe) {
            volume = 0;
        }
        if (data[0].equals(threeMonthDate)) {
            break;
        }

        OHLCDataItem item = new OHLCDataItem(date, open, high, low, close, volume);
        dataItems.add(item);
    }
    Collections.reverse(dataItems);

    OHLCDataItem[] OHLCData = dataItems.toArray(new OHLCDataItem[dataItems.size()]);
    return OHLCData;
}

From source file:com.reignite.parser.QueryParser.java

/**
 * Handles the case where a value for a criterion needs to be converted into
 * a native format like a date. To create native object use format like:
 * !Date(string,pattern) eg: Date(12/31/2013,dd/mm/yyyy)
 * //from   w ww.  ja  va2 s .c o  m
 * @param object
 * @return
 */
public Object createValue(Object object) throws ParserException {
    Object value = object;
    if (object instanceof String) {
        if (object == null || object.toString().toLowerCase().equals("null")) {
            return null;
        }
        String string = (String) object;
        if (string != null) {
            if (string.startsWith("!")) {
                string = string.substring(1);
                String typeString = string.substring(0, string.indexOf("("));
                if (typeString.toLowerCase().equals("date")) {
                    String dateString = string.substring(string.indexOf("(") + 1, string.indexOf(","));
                    String pattern = string.substring(string.indexOf(",") + 1, string.indexOf(")"));
                    DateFormat df = new SimpleDateFormat(pattern);
                    try {
                        value = df.parse(dateString);
                    } catch (ParseException e) {
                        throw new ParserException("Failed to parse date: " + dateString + " of pattern: "
                                + pattern + " Cause: " + e, e);
                    }
                }
            } else if (string.startsWith("\\")) {
                value = string.substring(1);
            }
        }
    } else if (object != null && JSONObject.NULL.equals(object)) {
        value = null;
    }
    return value;
}

From source file:com.charts.FiveYearChart.java

protected OHLCDataItem[] getData(YStockQuote currentStock) throws ParseException {
    ArrayList<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>();
    DateFormat df;
    if (currentStock instanceof Index)
        df = new SimpleDateFormat("y-MM-dd");
    else/* w  w  w  .j  ava 2s .  c  om*/
        df = new SimpleDateFormat("dd-MM-yy");
    String FiveYearDate = df.format(DayRange.five_year);
    ArrayList<String> historicalData = currentStock.get_historical_data();
    int startIndex = currentStock.find_historical_data_index(FiveYearDate);
    while (startIndex > 0) {
        String[] data = historicalData.get(startIndex).split(",");

        Date date = df.parse(data[0]);
        double open = Double.parseDouble(data[1]);
        double high = Double.parseDouble(data[2]);
        double low = Double.parseDouble(data[3]);
        double close = Double.parseDouble(data[4]);
        this.close.addOrUpdate(new Day(date), close);
        double volume;
        try {
            volume = Double.parseDouble(data[5]);
        } catch (NumberFormatException nfe) {
            volume = 0;
        }

        OHLCDataItem item = new OHLCDataItem(date, open, high, low, close, volume);
        dataItems.add(item);
        startIndex -= 2;
    }

    OHLCDataItem[] OHLCData = dataItems.toArray(new OHLCDataItem[dataItems.size()]);
    return OHLCData;
}

From source file:com.charts.TenYearChart.java

protected OHLCDataItem[] getData(YStockQuote currentStock) throws ParseException {
    ArrayList<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>();
    DateFormat df;
    if (currentStock instanceof Index)
        df = new SimpleDateFormat("y-MM-dd");
    else/*www.ja  va2s  . c o m*/
        df = new SimpleDateFormat("dd-MM-yy");
    String TenYearDate = df.format(DayRange.ten_year);
    ArrayList<String> historicalData = currentStock.get_historical_data();
    int startIndex = currentStock.find_historical_data_index(TenYearDate);
    while (startIndex > 0) {
        String[] data = historicalData.get(startIndex).split(",");

        Date date = df.parse(data[0]);
        double open = Double.parseDouble(data[1]);
        double high = Double.parseDouble(data[2]);
        double low = Double.parseDouble(data[3]);
        double close = Double.parseDouble(data[4]);
        this.close.addOrUpdate(new Day(date), close);
        double volume;
        try {
            volume = Double.parseDouble(data[5]);
        } catch (NumberFormatException nfe) {
            volume = 0;
        }
        OHLCDataItem item = new OHLCDataItem(date, open, high, low, close, volume);
        dataItems.add(item);
        startIndex -= 3;
    }

    OHLCDataItem[] OHLCData = dataItems.toArray(new OHLCDataItem[dataItems.size()]);
    return OHLCData;
}

From source file:org.kepler.plotting.Plot.java

private void initializeDemoSeries() {
    DateFormat df = new SimpleDateFormat("M/d/yyyy HH:mm:ss.SSS");
    Date d0 = null, d1 = null, d2 = null, d3 = null, d4 = null;
    Date d5 = null, d6 = null, d7 = null, d8 = null, d9 = null;
    Date d10 = null, d11 = null, d12 = null, d13 = null, d14 = null;
    Date d15 = null;//from  w  w w .  ja v a 2 s . c o m
    try {
        d0 = df.parse("11/5/2003 0:00:00.000");
        d1 = df.parse("11/5/2003 0:01:00.000");
        d2 = df.parse("11/5/2003 0:02:00.000");
        d3 = df.parse("11/5/2003 0:03:00.000");
        d4 = df.parse("11/5/2003 0:04:00.000");
        d5 = df.parse("11/5/2003 0:05:00.000");
        d6 = df.parse("11/5/2003 0:06:00.000");
        d7 = df.parse("11/5/2003 0:07:00.000");
        d8 = df.parse("11/5/2003 0:08:00.000");
        d9 = df.parse("11/5/2003 0:09:00.000");
        d10 = df.parse("11/5/2003 0:10:00.000");
        d11 = df.parse("11/5/2003 0:11:00.000");
        d12 = df.parse("11/5/2003 0:12:00.000");
        d13 = df.parse("11/5/2003 0:13:00.000");
        d14 = df.parse("11/5/2003 0:14:00.000");
        d15 = df.parse("11/5/2003 0:15:00.000");
    } catch (ParseException ex) {
        ex.printStackTrace();
    }

    demoSeries.add(new SimpleTimePeriod(d0, d0), 0);
    demoSeries.add(new SimpleTimePeriod(d1, d1), 40.674);
    demoSeries.add(new SimpleTimePeriod(d2, d2), 74.314);
    demoSeries.add(new SimpleTimePeriod(d3, d3), 95.106);
    demoSeries.add(new SimpleTimePeriod(d4, d4), 99.452);
    demoSeries.add(new SimpleTimePeriod(d5, d5), 86.603);
    demoSeries.add(new SimpleTimePeriod(d6, d6), 58.779);
    demoSeries.add(new SimpleTimePeriod(d7, d7), 20.791);
    demoSeries.add(new SimpleTimePeriod(d8, d8), -20.791);
    demoSeries.add(new SimpleTimePeriod(d9, d9), -58.779);
    demoSeries.add(new SimpleTimePeriod(d10, d10), -86.603);
    demoSeries.add(new SimpleTimePeriod(d11, d11), -99.452);
    demoSeries.add(new SimpleTimePeriod(d12, d12), -95.106);
    demoSeries.add(new SimpleTimePeriod(d13, d13), -74.314);
    demoSeries.add(new SimpleTimePeriod(d14, d14), -40.674);
    demoSeries.add(new SimpleTimePeriod(d15, d15), 0);
}

From source file:com.cloudera.sqoop.manager.OracleManagerTest.java

/**
 * Compare two lines. Normalize the dates we receive based on the expected
 * time zone./* ww  w.  j  a  v a2 s. c o m*/
 * @param expectedLine    expected line
 * @param receivedLine    received line
 * @throws IOException    exception during lines comparison
 */
private void compareRecords(String expectedLine, String receivedLine) throws IOException {
    // handle null case
    if (expectedLine == null || receivedLine == null) {
        return;
    }

    // check if lines are equal
    if (expectedLine.equals(receivedLine)) {
        return;
    }

    // check if size is the same
    String[] expectedValues = expectedLine.split(",");
    String[] receivedValues = receivedLine.split(",");
    if (expectedValues.length != 7 || receivedValues.length != 7) {
        LOG.error("Number of expected fields did not match " + "number of received fields");
        throw new IOException("Number of expected fields did not match " + "number of received fields");
    }

    // check first 5 values
    boolean mismatch = false;
    for (int i = 0; !mismatch && i < 5; i++) {
        mismatch = !expectedValues[i].equals(receivedValues[i]);
    }
    if (mismatch) {
        throw new IOException("Expected:<" + expectedLine + "> but was:<" + receivedLine + ">");
    }

    Date expectedDate = null;
    Date receivedDate = null;
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
    int offset = TimeZone.getDefault().getOffset(System.currentTimeMillis()) / 3600000;
    for (int i = 5; i < 7; i++) {
        // parse expected timestamp.
        try {
            expectedDate = df.parse(expectedValues[i]);
        } catch (ParseException ex) {
            LOG.error("Could not parse expected timestamp: " + expectedValues[i]);
            throw new IOException("Could not parse expected timestamp: " + expectedValues[i]);
        }

        // parse received timestamp
        try {
            receivedDate = df.parse(receivedValues[i]);
        } catch (ParseException ex) {
            LOG.error("Could not parse received timestamp: " + receivedValues[i]);
            throw new IOException("Could not parse received timestamp: " + receivedValues[i]);
        }

        // compare two timestamps considering timezone offset
        Calendar expectedCal = Calendar.getInstance();
        expectedCal.setTime(expectedDate);
        expectedCal.add(Calendar.HOUR, offset);

        Calendar receivedCal = Calendar.getInstance();
        receivedCal.setTime(receivedDate);

        if (!expectedCal.equals(receivedCal)) {
            throw new IOException("Expected:<" + expectedLine + "> but was:<" + receivedLine
                    + ">, while timezone offset is: " + offset);
        }
    }
}