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:pl.psnc.synat.wrdz.mdz.format.FileFormatVerifierBean.java

/**
 * Extracts a date from nodes matching the xpath expression in the given document.
 * /*from   w  w  w.  ja  va 2s . c om*/
 * If multiple dates match, the earliest date is returned.
 * 
 * @param document
 *            xml document to search
 * @param xpath
 *            xpath expression
 * @return earliest matching date, or <code>null</code> if no dates were found
 */
private Date extractDate(Document document, String xpath) {
    NodeList nodes = xpath(document, xpath);

    DateFormat format = new SimpleDateFormat(DATE_FORMAT);
    Date result = null;
    for (int i = 0; i < nodes.getLength(); i++) {
        try {
            Date newDate = format.parse(nodes.item(i).getNodeValue());
            if (result == null || result.after(newDate)) {
                result = newDate;
            }
        } catch (ParseException e) {
            logger.warn("Unparsable date retrieved from UDFR response: {}", nodes.item(i).getNodeValue());
        }
    }

    return result;
}

From source file:com.flozano.socialauth.provider.RunkeeperImpl.java

private Profile getProfile() throws Exception {
    String presp;/*from   w w  w. ja v a  2 s  .  c om*/
    try {
        Map<String, String> hmap = new HashMap<String, String>();
        hmap.put("Accept", "application/vnd.com.runkeeper.Profile+json");
        Response response = authenticationStrategy.executeFeed(PROFILE_URL, MethodType.GET.toString(), null,
                hmap, null);
        presp = response.getResponseBodyAsString(Constants.ENCODING);
    } catch (Exception e) {
        throw new SocialAuthException("Error while getting profile from " + PROFILE_URL, e);
    }
    try {
        LOG.debug("User Profile : " + presp);
        JSONObject resp = new JSONObject(presp);
        Profile p = new Profile();
        if (resp.has("profile")) {
            String purl = resp.getString("profile");
            String parr[] = purl.split("/");
            p.setValidatedId(parr[parr.length - 1]);
        }
        if (resp.has("name")) {
            p.setFirstName(resp.getString("name"));
            p.setFullName(resp.getString("name"));
        }

        if (resp.has("location")) {
            p.setLocation(resp.getString("location"));
        }
        if (resp.has("birthday")) {
            String bstr = resp.getString("birthday");
            if (bstr != null) {
                if (bstr.matches("[A-Za-z]{3}, \\d{1,2} [A-Za-z]{3} \\d{4} \\d{2}:\\d{2}:\\d{2}")) {
                    DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss");
                    Date d = df.parse(bstr);
                    Calendar c = Calendar.getInstance();
                    c.setTime(d);
                    BirthDate bd = new BirthDate();
                    bd.setDay(c.get(Calendar.DAY_OF_MONTH));
                    bd.setYear(c.get(Calendar.YEAR));
                    bd.setMonth(c.get(Calendar.MONTH) + 1);
                    p.setDob(bd);
                }
            }
        }
        if (resp.has("gender")) {
            p.setGender(resp.getString("gender"));
        }
        if (resp.has("normal_picture")) {
            p.setProfileImageURL(resp.getString("normal_picture"));
        }
        p.setProviderId(getProviderId());
        userProfile = p;
        return p;

    } catch (Exception ex) {
        throw new ServerDataException("Failed to parse the user profile json : " + presp, ex);
    }
}

From source file:com.luna.common.repository.search.SearchUserRepositoryIT.java

@Test
public void testLtAndGtForDate() throws ParseException {
    int count = 15;
    String dateStr = "2012-01-15 16:59:00";
    String dateStrFrom = "2012-01-15 16:58:00";
    String dateStrEnd = "2012-01-15 16:59:01";
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    for (int i = 0; i < count; i++) {
        User user = createUser();/*  w w w .  ja  v  a  2s.c o m*/
        user.getBaseInfo().setBirthday(new Timestamp(df.parse(dateStr).getTime()));
        userRepository.save(user);
    }
    Map<String, Object> searchParams = new HashMap<String, Object>();
    searchParams.put("baseInfo.birthday_gt", dateStrFrom);
    searchParams.put("baseInfo.birthday_lt", dateStrEnd);
    Searchable search = Searchable.newSearchable(searchParams);
    assertEquals(count, userRepository.count(search));
}

From source file:com.luna.common.repository.search.SearchUserRepositoryIT.java

@Test
public void testLteAndGteForDate() throws ParseException {
    int count = 15;
    String dateStr = "2012-01-15 16:59:00";
    String dateStrFrom = "2012-01-15 16:59:00";
    String dateStrEnd = "2012-01-15 16:59:00";
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    for (int i = 0; i < count; i++) {
        User user = createUser();/*  w w w.  j  av a  2 s .  c o m*/
        user.getBaseInfo().setBirthday(new Timestamp(df.parse(dateStr).getTime()));
        userRepository.save(user);
    }
    Map<String, Object> searchParams = new HashMap<String, Object>();
    searchParams.put("baseInfo.birthday_gte", dateStrFrom);
    searchParams.put("baseInfo.birthday_lte", dateStrEnd);
    Searchable search = Searchable.newSearchable(searchParams);
    assertEquals(count, userRepository.count(search));
}

From source file:com.nubits.nubot.utils.FrozenBalancesManager.java

private void parseFrozenBalancesFile() {
    JSONParser parser = new JSONParser();
    String FrozenBalancesManagerString = FilesystemUtils.readFromFile(this.pathToFrozenBalancesFiles);
    try {//from  w  w w  .j  a v  a 2s. com
        JSONObject frozenBalancesJSON = (JSONObject) (parser.parse(FrozenBalancesManagerString));
        double quantity = Double.parseDouble((String) frozenBalancesJSON.get("frozen-quantity-total"));
        Amount frozenAmount = new Amount(quantity, toFreezeCurrency);
        setInitialFrozenAmount(frozenAmount, false);

        JSONArray historyArr = (JSONArray) frozenBalancesJSON.get("history");
        for (int i = 0; i < historyArr.size(); i++) {
            JSONObject tempHistoryRow = (JSONObject) historyArr.get(i);

            DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
            Date timestamp = df.parse((String) tempHistoryRow.get("timestamp"));

            double frozeQuantity = Double.parseDouble((String) tempHistoryRow.get("froze-quantity"));
            String currencyCode = (String) tempHistoryRow.get("currency-code");

            history.add(new HistoryRow(timestamp, frozeQuantity, currencyCode));
        }

    } catch (ParseException | NumberFormatException | java.text.ParseException e) {
        LOG.error("Error while parsing the frozen balances file (" + pathToFrozenBalancesFiles + ")\n"
                + e.toString());
    }
}

From source file:com.all.client.model.TimeComparator.java

private Date parseDate(String date) throws ParseException {
    try {/* w w w.j  ava 2  s.  co  m*/
        DateFormat formater = new SimpleDateFormat("h:mm:ss");
        return formater.parse(date);
    } catch (ParseException e) {
        DateFormat formater = new SimpleDateFormat("m:ss");
        return formater.parse(date);
    }
}

From source file:dk.cafeanalog.AnalogDownloader.java

private ArrayList<Opening> getOpenings() throws IOException, JSONException, ParseException {
    if (System.currentTimeMillis() - mLastGet < TIME_BETWEEN_DOWNLOADS && mOpeningsCache != null) {
        return mOpeningsCache;
    }//from   w w  w. j  av a 2s.  c  o m
    mLastGet = System.currentTimeMillis();
    URL url = new URL("http", "cafeanalog.dk", "api/shifts");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setRequestMethod("GET");
    connection.connect();

    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringBuilder builder = new StringBuilder();
    String s;
    while ((s = reader.readLine()) != null) {
        builder.append(s);
    }

    JSONArray array = new JSONArray(builder.toString());

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZ", Locale.getDefault());

    ArrayList<Opening> openings = new ArrayList<>();

    for (int i = 0; i < array.length(); i++) {
        JSONObject object = array.getJSONObject(i);

        Date open = dateFormat.parse(object.getString("Open"));
        Date close = dateFormat.parse(object.getString("Close"));
        JSONArray nameArray = object.getJSONArray("Employees");
        List<String> names = new ArrayList<>();

        for (int j = 0; j < nameArray.length(); j++) {
            names.add(nameArray.getString(j));
        }

        openings.add(new Opening(open, close, names));
    }
    mOpeningsCache = openings;
    return openings;
}

From source file:com.orangesignal.csv.SpringTest.java

@Test
public void testCsvBeanManager() throws Exception {
    assertThat(manager, notNullValue());
    final Reader reader = new StringReader(
            "symbol,name,price,volume,date\r\n" + "GCQ09,COMEX  200908?,1058.70,10,2008/08/06\r\n"
                    + "GCU09,COMEX  200909?,1068.70,10,2008/09/06\r\n"
                    + "GCV09,COMEX  200910?,1078.70,11,2008/10/06\r\n"
                    + "GCX09,COMEX  200911?,1088.70,12,2008/11/06\r\n"
                    + "GCZ09,COMEX  200912?,1098.70,13,2008/12/06\r\n");

    try {//from w  ww  .ja  va 2 s  .  c  o  m
        final DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
        final List<SampleBean> list = manager.load(SampleBean.class)
                .format("date", new SimpleDateFormat("yyyy/MM/dd"))
                .filter(new SimpleCsvNamedValueFilter().ne("symbol", "gcu09", true))
                .filter(new SimpleBeanFilter().ne("date", df.parse("2008/11/06"))).offset(1).limit(1)
                .from(reader);

        assertThat(list.size(), is(1));
        final SampleBean o1 = list.get(0);
        assertThat(o1.symbol, is("GCV09"));
        assertThat(o1.name, is("COMEX  200910?"));
        assertThat(o1.price.doubleValue(), is(1078.70D));
        assertThat(o1.volume.longValue(), is(11L));
        assertThat(o1.date, is(df.parse("2008/10/06")));
    } finally {
        reader.close();
    }
}

From source file:com.streamsets.pipeline.stage.processor.fieldvaluereplacer.FieldValueReplacerProcessor.java

private Object convertToType(String stringValue, Field.Type fieldType, String matchingField)
        throws ParseException {
    switch (fieldType) {
    case BOOLEAN:
        return Boolean.valueOf(stringValue);
    case BYTE:/*  w w  w . j ava2s .co  m*/
        return Byte.valueOf(stringValue);
    case BYTE_ARRAY:
        return stringValue.getBytes(StandardCharsets.UTF_8);
    case CHAR:
        return stringValue.charAt(0);
    case DATE:
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
        return dateFormat.parse(stringValue);
    case TIME:
        DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
        return timeFormat.parse(stringValue);
    case DATETIME:
        DateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ", Locale.ENGLISH);
        return dateTimeFormat.parse(stringValue);
    case DECIMAL:
        return new BigDecimal(stringValue);
    case DOUBLE:
        return Double.valueOf(stringValue);
    case FLOAT:
        return Float.valueOf(stringValue);
    case INTEGER:
        return Integer.valueOf(stringValue);
    case LONG:
        return Long.valueOf(stringValue);
    case SHORT:
        return Short.valueOf(stringValue);
    case FILE_REF:
        throw new IllegalArgumentException(
                Utils.format(Errors.VALUE_REPLACER_03.getMessage(), fieldType, matchingField));
    case LIST_MAP:
    case LIST:
    case MAP:
    default:
        return stringValue;
    }
}

From source file:com.dagobert_engine.portfolio.service.MtGoxPortfolioService.java

/**
 * Get last login//  ww w .  j a va 2s  . com
 * 
 * @param forceRefresh
 * @return
 */
public Date getLastLogin() {

    DateFormat df = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
    try {
        return df.parse((String) getData().get("Last_Login"));
    } catch (java.text.ParseException e) {
        throw new MtGoxException(e);
    }
}