Java Code Examples for java.text.DateFormat#parse()

The following examples show how to use java.text.DateFormat#parse() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: JobX   File: DateUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static int compare_date(String DATE1, String DATE2) {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
    try {
        Date dt1 = df.parse(DATE1);
        Date dt2 = df.parse(DATE2);
        if (dt1.getTime() > dt2.getTime()) {

            return 1;
        } else if (dt1.getTime() < dt2.getTime()) {

            return -1;
        } else {
            return 0;
        }
    } catch (Exception exception) {
        exception.printStackTrace();
    }
    return 0;
}
 
Example 2
Source Project: StatsAgg   File: DateAndTime.java    License: Apache License 2.0 6 votes vote down vote up
public static Date getDateFromFormattedString(String dateAndTime, String simpleDateFormat) {
    
    if ((dateAndTime == null) || (simpleDateFormat == null)) {
        return null;
    }
    
    try {
        DateFormat formatter = new SimpleDateFormat(simpleDateFormat);
        Date dateDateAndTime = formatter.parse(dateAndTime);
        
        return dateDateAndTime;
    }
    catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
        return null;
    }
}
 
Example 3
Source Project: onetwo   File: DateConverter.java    License: Apache License 2.0 6 votes vote down vote up
protected Object convertToDate(Class type, Object value, String pattern) {
    DateFormat df = new SimpleDateFormat(pattern);
    if (value instanceof String) {
        try {
            if (StringUtils.isEmpty(value.toString())) {
                return null;
            }

            Date date = df.parse((String) value);
            if (type.equals(Timestamp.class)) {
                return new Timestamp(date.getTime());
            }
            return date;
        } catch (Exception pe) {
            pe.printStackTrace();
            throw new ConversionException("Error converting String to Date");
        }
    }

    throw new ConversionException("Could not convert " +
                                  value.getClass().getName() + " to " +
                                  type.getName());
}
 
Example 4
Source Project: netbeans   File: TimeType.java    License: Apache License 2.0 5 votes vote down vote up
private synchronized static Date doParse (String sVal) {
    Date dVal = null;
    for (DateFormat format : TIME_PARSING_FORMATS) {
        try {
            dVal = format.parse (sVal);
            break;
        } catch (ParseException ex) {
            Logger.getLogger (TimeType.class.getName ()).log (Level.FINEST, ex.getLocalizedMessage () , ex);
        }
    }
    return dVal;
}
 
Example 5
@Test
public void testTimeZone() throws ParseException
{
  final DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
  df.setTimeZone(DateHelper.EUROPE_BERLIN);
  final Date mezDate = df.parse("2008-03-14 17:25");
  final long mezMillis = mezDate.getTime();
  df.setTimeZone(DateHelper.UTC);
  final Date utcDate = df.parse("2008-03-14 16:25");
  final long utcMillis = utcDate.getTime();
  assertEquals(mezMillis, utcMillis);
}
 
Example 6
@Test
public void eqFilterOnDate() throws Exception {
	DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
	Date date;
	date = format.parse("01/01/2008");
	Filter filter = filterCreator.createCompareFilter(ATTR__ONE_TO_MANY__DOT__DATE, "==", date);
	Iterator<?> it = layer.getElements(filter, 0, 0);
	int t = 0;
	while (it.hasNext()) {
		Assert.assertTrue("Returned object must be a HibernateTestFeature",
				it.next() instanceof HibernateTestFeature);
		t++;
	}
	Assert.assertEquals(2, t);
}
 
Example 7
@Test
public void testGetDateArrayWithFormat() throws Exception
{
    final DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
    final Date date1 = format.parse("01/01/2004");
    final Date date2 = format.parse("12/31/2004");
    final Date[] expected = new Date[] { date1, date2 };

    conf.addProperty("date.format", "01/01/2004");
    conf.addProperty("date.format", "12/31/2004");
    ArrayAssert.assertEquals("Wrong dates with format", expected, conf.getDateArray("date.format", "MM/dd/yyyy"));
}
 
Example 8
Source Project: ormlite-jdbc   File: JdbcBaseDaoImplTest.java    License: ISC License 5 votes vote down vote up
@Test
public void testDefaultValueHandling() throws Exception {
	Dao<AllTypesDefault, Object> allDao = createDao(AllTypesDefault.class, true);
	AllTypesDefault all = new AllTypesDefault();
	assertEquals(1, allDao.create(all));
	assertEquals(1, allDao.refresh(all));
	List<AllTypesDefault> allList = allDao.queryForAll();
	assertEquals(1, allList.size());
	all.stringField = DEFAULT_STRING_VALUE;
	DateFormat defaultDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS", Locale.US);
	all.dateField = defaultDateFormat.parse(DEFAULT_DATE_VALUE);
	all.dateLongField = new Date(Long.parseLong(DEFAULT_DATE_LONG_VALUE));
	DateFormat defaultDateStringFormat = new SimpleDateFormat(DEFAULT_DATE_STRING_FORMAT, Locale.US);
	all.dateStringField = defaultDateStringFormat.parse(DEFAULT_DATE_STRING_VALUE);
	all.booleanField = Boolean.parseBoolean(DEFAULT_BOOLEAN_VALUE);
	all.booleanObj = Boolean.parseBoolean(DEFAULT_BOOLEAN_VALUE);
	all.byteField = Byte.parseByte(DEFAULT_BYTE_VALUE);
	all.byteObj = Byte.parseByte(DEFAULT_BYTE_VALUE);
	all.shortField = Short.parseShort(DEFAULT_SHORT_VALUE);
	all.shortObj = Short.parseShort(DEFAULT_SHORT_VALUE);
	all.intField = Integer.parseInt(DEFAULT_INT_VALUE);
	all.intObj = Integer.parseInt(DEFAULT_INT_VALUE);
	all.longField = Long.parseLong(DEFAULT_LONG_VALUE);
	all.longObj = Long.parseLong(DEFAULT_LONG_VALUE);
	all.floatField = Float.parseFloat(DEFAULT_FLOAT_VALUE);
	all.floatObj = Float.parseFloat(DEFAULT_FLOAT_VALUE);
	all.doubleField = Double.parseDouble(DEFAULT_DOUBLE_VALUE);
	all.doubleObj = Double.parseDouble(DEFAULT_DOUBLE_VALUE);
	all.ourEnum = OurEnum.valueOf(DEFAULT_ENUM_VALUE);
	assertFalse(allDao.objectsEqual(all, allList.get(0)));
}
 
Example 9
@SuppressWarnings("unchecked")
protected <T> T cast(DefaultJSONParser parser, Type clazz, Object fieldName, Object val) {

    if (val == null) {
        return null;
    }

    if (val instanceof java.util.Date) {
        return (T) new java.sql.Timestamp(((Date) val).getTime());
    }

    if (val instanceof Number) {
        return (T) new java.sql.Timestamp(((Number) val).longValue());
    }

    if (val instanceof String) {
        String strVal = (String) val;
        if (strVal.length() == 0) {
            return null;
        }

        DateFormat dateFormat = parser.getDateFormat();
        try {
            Date date = (Date) dateFormat.parse(strVal);
            return (T) new Timestamp(date.getTime());
        } catch (ParseException e) {
            // skip
        }

        long longVal = Long.parseLong(strVal);
        return (T) new java.sql.Timestamp(longVal);
    }

    throw new JSONException("parse error");
}
 
Example 10
Source Project: netbeans   File: DateType.java    License: Apache License 2.0 5 votes vote down vote up
private synchronized static java.util.Date doParse (String sVal) {
    java.util.Date dVal = null;
    for (DateFormat format : DATE_PARSING_FORMATS) {
        try {
            dVal = format.parse (sVal);
            break;
        } catch (ParseException ex) {
            Logger.getLogger (DateType.class.getName ()).log (Level.FINEST, ex.getLocalizedMessage () , ex);
        }
    }
    return dVal;
}
 
Example 11
@Test
public void neFilterOnDate() throws Exception {
	DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
	Date date;
	date = format.parse("01/01/2008");
	Filter filter = filterCreator.createCompareFilter(MTO_DATE, "<>", date);
	Iterator<?> it = layer.getElements(filter, 0, 0);
	int t = 0;
	while (it.hasNext()) {
		Assert.assertTrue("Returned object must be a AssociationFeature", it.next() instanceof AssociationFeature);
		t++;
	}
	Assert.assertEquals(3, t);
}
 
Example 12
Source Project: JavaRushTasks   File: LogParser.java    License: MIT License 5 votes vote down vote up
private Date getDate(String part) {
    DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss", Locale.ENGLISH);
    Date date = null;
    try {
        date = dateFormat.parse(part);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
}
 
Example 13
/**
 * Creates a new KmlTrack object
 *
 * @return KmlTrack object
 */
private static KmlTrack createTrack(XmlPullParser parser)
        throws XmlPullParserException, IOException {
    DateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.getDefault());
    iso8601.setTimeZone(TimeZone.getTimeZone("UTC"));
    ArrayList<LatLng> latLngs = new ArrayList<LatLng>();
    ArrayList<Double> altitudes = new ArrayList<Double>();
    ArrayList<Long> timestamps = new ArrayList<Long>();
    HashMap<String, String> properties = new HashMap<>();
    int eventType = parser.getEventType();
    while (!(eventType == END_TAG && parser.getName().equals("Track"))) {
        if (eventType == START_TAG) {
            if (parser.getName().equals("coord")) {
                String coordinateString = parser.nextText();
                //fields are separated by spaces instead of commas
                LatLngAlt latLngAlt = convertToLatLngAlt(coordinateString, " ");
                latLngs.add(latLngAlt.latLng);
                if (latLngAlt.altitude != null) {
                    altitudes.add(latLngAlt.altitude);
                }
            } else if (parser.getName().equals("when")) {
                try {
                    String dateString = parser.nextText();
                    Date date = iso8601.parse(dateString);
                    long millis = date.getTime();

                    timestamps.add(millis);
                } catch (ParseException e) {
                    throw new XmlPullParserException("Invalid date", parser, e);
                }
            } else if (parser.getName().equals(EXTENDED_DATA)) {
                properties.putAll(setExtendedDataProperties(parser));
            }
        }
        eventType = parser.next();
    }
    return new KmlTrack(latLngs, altitudes, timestamps, properties);
}
 
Example 14
Source Project: watchlist   File: ReviewFragment.java    License: Apache License 2.0 4 votes vote down vote up
private void downloadMovieReviews() {
    if (adapter == null) {
        adapter = new ReviewAdapter(new ArrayList<Review>(), this);
        reviewList.setAdapter(adapter);
    }
    JsonArrayRequest request = new JsonArrayRequest(
            Request.Method.GET, ApiHelper.getMovieReviewsLink(movieId, pageToDownload), null,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray array) {
                    try {
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject review = array.getJSONObject(i);

                            String id = review.getString("id");
                            String comment = review.getString("comment");
                            boolean hasSpoiler = review.getBoolean("spoiler");

                            // Get date and format it
                            String inputTime = review.getString("created_at").substring(0, 10);
                            DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
                            Date date = inputFormat.parse(inputTime);
                            DateFormat outputFormat = new SimpleDateFormat("dd MMM yyyy");
                            String createdAt = outputFormat.format(date);

                            // Get user name
                            JSONObject user = review.getJSONObject("user");
                            String userName = user.getString("username");
                            if (!user.getBoolean("private")) {
                                String name = user.getString("name");
                                if (!TextUtil.isNullOrEmpty(name)) {
                                    userName = name;
                                }
                            }

                            adapter.reviewList.add(new Review(id, userName, comment, createdAt, hasSpoiler));
                        }

                        onDownloadSuccessful();

                    } catch (Exception ex) {
                        // Parsing error
                        onDownloadFailed();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    if (volleyError.networkResponse.statusCode == 404 || volleyError.networkResponse.statusCode == 405) {
                        // No such movie exists
                        onDownloadSuccessful();
                    } else {
                        // Network error, failed to load
                        onDownloadFailed();
                    }
                }
            }) {
                // Add Request Headers
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String>  params = new HashMap<>();
                    params.put("Content-type", "application/json");
                    params.put("trakt-api-key", ApiHelper.getTraktKey(getContext()));
                    params.put("trakt-api-version", "2");
                    return params;
                }
                // Get Response Headers
                @Override
                protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
                    pageToDownload = Integer.parseInt(response.headers.get("X-Pagination-Page")) + 1;
                    totalPages = Integer.parseInt(response.headers.get("X-Pagination-Page-Count"));
                    return super.parseNetworkResponse(response);
                }
            };
    isLoading = true;
    request.setTag(getClass().getName());
    VolleySingleton.getInstance().requestQueue.add(request);
}
 
Example 15
@Test
public void runTest() throws Exception {
    AAPSMocker.mockMainApp();
    AAPSMocker.mockApplicationContext();

    TimeZone tz = TimeZone.getTimeZone("Europe/Rome");
    TimeZone.setDefault(tz);
    Calendar cal = Calendar.getInstance(tz, Locale.ITALIAN);
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ITALIAN);
    Date dateBeforeDST = df.parse("2018-03-25 01:55");
    cal.setTime(dateBeforeDST);
    Assert.assertEquals(false, plugin.wasDST(cal));
    Assert.assertEquals(true, plugin.willBeDST(cal));


    TimeZone.setDefault(tz);
    cal = Calendar.getInstance(tz, Locale.ITALIAN);
    dateBeforeDST = df.parse("2018-03-25 03:05");
    cal.setTime(dateBeforeDST);
    Assert.assertEquals(true, plugin.wasDST(cal));
    Assert.assertEquals(false, plugin.willBeDST(cal));


    TimeZone.setDefault(tz);
    cal = Calendar.getInstance(tz, Locale.ITALIAN);
    dateBeforeDST = df.parse("2018-03-25 02:05"); //Cannot happen!!!
    cal.setTime(dateBeforeDST);
    Assert.assertEquals(true, plugin.wasDST(cal));
    Assert.assertEquals(false, plugin.willBeDST(cal));

    TimeZone.setDefault(tz);
    cal = Calendar.getInstance(tz, Locale.ITALIAN);
    dateBeforeDST = df.parse("2018-03-25 05:55"); //Cannot happen!!!
    cal.setTime(dateBeforeDST);
    Assert.assertEquals(true, plugin.wasDST(cal));
    Assert.assertEquals(false, plugin.willBeDST(cal));

    TimeZone.setDefault(tz);
    cal = Calendar.getInstance(tz, Locale.ITALIAN);
    dateBeforeDST = df.parse("2018-03-25 06:05"); //Cannot happen!!!
    cal.setTime(dateBeforeDST);
    Assert.assertEquals(false, plugin.wasDST(cal));
    Assert.assertEquals(false, plugin.willBeDST(cal));

}
 
Example 16
/**
 * @throws Exception If failed.
 */
@Test
public void testPutComplexObject() throws Exception {
    String cacheName = "complex";

    DateFormat df = JSON_MAPPER.getDateFormat();

    OuterClass[] objects = new OuterClass[] {
        new OuterClass(111, "out-0", 0.7d, F.asList(9, 1)),
        new OuterClass(112, "out-1", 0.1d, F.asList(9, 1)),
        new OuterClass(113, "out-2", 0.3d, F.asList(9, 1))
    };

    Complex complex = new Complex(
        1234567,
        "String value",
        new Timestamp(Calendar.getInstance().getTime().getTime()),
        Date.valueOf("1986-04-26"),
        Time.valueOf("23:59:59"),
        df.parse(df.format(Calendar.getInstance().getTime())),
        F.asMap("key1", 1, "key2", 2),
        new int[] {1, 2, 3},
        F.asList(11, 22, 33).toArray(new Integer[3]),
        new long[] {Long.MIN_VALUE, 0, Long.MAX_VALUE},
        F.asList(4, 5, 6),
        F.asMap(123, null, 4567, null).keySet(),
        new byte[] {4, 1, 2},
        new char[] {'a', 'b', 'c'},
        Color.GREEN,
        new OuterClass(Long.MIN_VALUE, "outer", 0.7d, F.asList(9, 1)),
        objects,
        UUID.randomUUID(),
        IgniteUuid.randomUuid()
    );

    putObject(cacheName, "300", complex);

    assertEquals(complex, getObject(cacheName, "300", Complex.class));
    assertEquals(complex, grid(0).cache(cacheName).get(300));

    // Check query result.
    JsonNode res = queryObject(
        cacheName,
        GridRestCommand.EXECUTE_SQL_QUERY,
        "type", Complex.class.getSimpleName(),
        "pageSize", "1",
        "qry", "sqlDate > ? and sqlDate < ?",
        "arg1", "1953-03-05",
        "arg2", "2011-03-11"
    );

    assertEquals(complex, JSON_MAPPER.treeToValue(res, Complex.class));
}
 
Example 17
Source Project: TestingApp   File: ListicatorListTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void ownerCanChange() throws ParseException {

    ListicatorList list = new ListicatorList("My New List","This is a list of my cool stuff");

    list.forceSetCreatedDate("2016-04-01-01-01-01");
    list.forceSetAmendedDate("2016-04-01-01-01-01");

    Assert.assertEquals("", list.getOwner());

    list.setOwner("bob");

    Assert.assertEquals("bob", list.getOwner());

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

    Date createdDate = dateFormat.parse(list.getCreatedDate());
    Date amendedDate = dateFormat.parse(list.getAmendedDate());
    Assert.assertTrue(amendedDate.after(createdDate));
}
 
Example 18
Source Project: scipio-erp   File: UtilDateTime.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Localized String to Timestamp conversion. To be used in tandem with timeStampToString().
 */
public static Timestamp stringToTimeStamp(String dateTimeString, String dateTimeFormat, TimeZone tz, Locale locale) throws ParseException {
    DateFormat dateFormat = toDateTimeFormat(dateTimeFormat, tz, locale);
    Date parsedDate = dateFormat.parse(dateTimeString);
    return new Timestamp(parsedDate.getTime());
}
 
Example 19
protected Date createDateFromLocalString(String dateString) throws ParseException {
  // Format: 2015-10-25T02:50:00 CEST
  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss z", Locale.US);
  return dateFormat.parse(dateString);
}
 
Example 20
Source Project: p4ic4idea   File: ClientProgressReport.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Parses the date.
 *
 * @param date
 *            the date
 * @param pattern
 *            the pattern
 * @return the date
 * @throws ParseException
 *             the parse exception
 */
private Date parseDate(String date, String pattern) throws ParseException {
    Date d = null;
    if (date != null) {
        DateFormat df = new SimpleDateFormat(pattern);
        d = df.parse(date);
    }
    return d;
}