Java Code Examples for org.apache.commons.lang3.time.DateUtils#parseDate()

The following examples show how to use org.apache.commons.lang3.time.DateUtils#parseDate() . 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 check out the related API usage on the sidebar.
Example 1
Source File: TimeConvertListener.java    From MooTool with MIT License 6 votes vote down vote up
private static void toTimestamp() {
    TimeConvertForm timeConvertForm = TimeConvertForm.getInstance();
    try {
        String localTime = timeConvertForm.getGmtTextField().getText();
        String unit = (String) timeConvertForm.getUnitComboBox().getSelectedItem();
        Date date = DateUtils.parseDate(localTime, TimeConvertForm.TIME_FORMAT);
        long timeStamp = date.getTime();
        if ("秒(s)".equals(unit)) {
            timeStamp = timeStamp / 1000;
        }
        timeConvertForm.getTimestampTextField().setText(String.valueOf(timeStamp));
        timeConvertForm.getTimestampTextField().grabFocus();
    } catch (Exception ex) {
        ex.printStackTrace();
        logger.error(ExceptionUtils.getStackTrace(ex));
        JOptionPane.showMessageDialog(timeConvertForm.getTimeConvertPanel(), ex.getMessage(), "转换失败!", JOptionPane.ERROR_MESSAGE);
    }
}
 
Example 2
Source File: HttpHeaderApplicationUserBuilder.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Gets an HTTP header date value from the map of headers for the specified header name. If the header value is blank or can't be converted to a Date, null
 * will be returned in its place.
 *
 * @param headerName the HTTP header name to get.
 * @param httpHeaders the HTTP headers.
 *
 * @return the HTTP header value.
 */
public Date getHeaderValueDate(String headerName, Map<String, String> httpHeaders)
{
    // Default the return value to null.
    Date dateValue = null;

    // Get the string value for the header name.
    String stringValue = getHeaderValueString(headerName, httpHeaders);

    // Try to convert it to a Date if possible
    if (stringValue != null)
    {
        try
        {
            dateValue = DateUtils.parseDate(stringValue, CALENDAR_PATTERNS);
        }
        catch (Exception ex)
        {
            // The value couldn't be converted to a Date so leave the dateValue null.
            dateValue = null;
        }
    }

    // Return the calendar value.
    return dateValue;
}
 
Example 3
Source File: WebClient2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
* @throws Exception if the test fails
*/
 @Test
 public void buildCookie() throws Exception {
     checkCookie("", EMPTY_COOKIE_NAME, "", "/", false, null);
     checkCookie("toto", EMPTY_COOKIE_NAME, "toto", "/", false, null);
     checkCookie("toto=", "toto", "", "/", false, null);
     checkCookie("toto=foo", "toto", "foo", "/", false, null);
     checkCookie("toto=foo;secure", "toto", "foo", "/", true, null);
     checkCookie("toto=foo;path=/myPath;secure", "toto", "foo", "/myPath", true, null);

     // Check that leading and trailing whitespaces are ignored
     checkCookie("  toto", EMPTY_COOKIE_NAME, "toto", "/", false, null);
     checkCookie("  = toto", EMPTY_COOKIE_NAME, "toto", "/", false, null);
     checkCookie("   toto=foo;  path=/myPath  ; secure  ",
           "toto", "foo", "/myPath", true, null);

     // Check that we accept reserved attribute names (e.g expires, domain) in any case
     checkCookie("toto=foo; PATH=/myPath; SeCURE",
           "toto", "foo", "/myPath", true, null);

     // Check that we are able to parse and set the expiration date correctly
     final String dateString = "Fri, 21 Jul 2023 20:47:11 UTC";
     final Date date = DateUtils.parseDate(dateString, "EEE, dd MMM yyyy HH:mm:ss z");
     checkCookie("toto=foo; expires=" + dateString, "toto", "foo", "/", false, date);
 }
 
Example 4
Source File: StringToDateConverter.java    From spring-cloud-gray with Apache License 2.0 6 votes vote down vote up
@Override
public Date convert(String source) {
    source = StringUtils.strip(source);
    Assert.hasText(source, "Null or emtpy date string");
    Date date = null;
    try {
        date = DateUtils.parseDate(source, dateFormats);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
    }
    if (date == null) {
        String errMsg = String.format("Failed to convert [%s] to [%s] for value '%s'",
                String.class.toString(), Date.class.toString(), source);
        log.error(errMsg);
        throw new IllegalArgumentException(errMsg);
    }

    return date;

}
 
Example 5
Source File: DateTools.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Date parseDateTime(String str) throws Exception {
	if (isDateTime(str) || isCompactDateTime(str)) {
		return DateUtils.parseDate(str, new String[] { format_yyyyMMddHHmmss, formatCompact_yyyyMMddHHmmss });
	} else {
		return null;
	}
}
 
Example 6
Source File: DateConstraintValidator.java    From Milkomeda with MIT License 5 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
    // 如果为空就不验证
    if (null == value || "".equals(value)) return true;
    try {
        DateUtils.parseDate(value, dateFormat);
        return true;
    } catch (Exception e) {
        return false;
    }
}
 
Example 7
Source File: JobLogController.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/pageList")
@ResponseBody
public Map<String, Object> pageList(@RequestParam(required = false, defaultValue = "0") int start,  
		@RequestParam(required = false, defaultValue = "10") int length,
		int jobGroup, int jobId, int logStatus, String filterTime) {
	
	// parse param
	Date triggerTimeStart = null;
	Date triggerTimeEnd = null;
	if (StringUtils.isNotBlank(filterTime)) {
		String[] temp = filterTime.split(" - ");
		if (temp!=null && temp.length == 2) {
			try {
				triggerTimeStart = DateUtils.parseDate(temp[0], new String[]{"yyyy-MM-dd HH:mm:ss"});
				triggerTimeEnd = DateUtils.parseDate(temp[1], new String[]{"yyyy-MM-dd HH:mm:ss"});
			} catch (ParseException e) {	}
		}
	}
	
	// page query
	List<XxlJobLog> list = xxlJobLogDao.pageList(start, length, jobGroup, jobId, triggerTimeStart, triggerTimeEnd, logStatus);
	int list_count = xxlJobLogDao.pageListCount(start, length, jobGroup, jobId, triggerTimeStart, triggerTimeEnd, logStatus);
	
	// package result
	Map<String, Object> maps = new HashMap<String, Object>();
    maps.put("recordsTotal", list_count);		// 总记录数
    maps.put("recordsFiltered", list_count);	// 过滤后的总记录数
    maps.put("data", list);  					// 分页列表
	return maps;
}
 
Example 8
Source File: JobLogController.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/pageList")
@ResponseBody
public Map<String, Object> pageList(@RequestParam(required = false, defaultValue = "0") int start,  
		@RequestParam(required = false, defaultValue = "10") int length,
		int jobGroup, int jobId, int logStatus, String filterTime) {
	
	// parse param
	Date triggerTimeStart = null;
	Date triggerTimeEnd = null;
	if (StringUtils.isNotBlank(filterTime)) {
		String[] temp = filterTime.split(" - ");
		if (temp!=null && temp.length == 2) {
			try {
				triggerTimeStart = DateUtils.parseDate(temp[0], new String[]{"yyyy-MM-dd HH:mm:ss"});
				triggerTimeEnd = DateUtils.parseDate(temp[1], new String[]{"yyyy-MM-dd HH:mm:ss"});
			} catch (ParseException e) {	}
		}
	}
	
	// page query
	List<XxlJobLog> list = xxlJobLogDao.pageList(start, length, jobGroup, jobId, triggerTimeStart, triggerTimeEnd, logStatus);
	int list_count = xxlJobLogDao.pageListCount(start, length, jobGroup, jobId, triggerTimeStart, triggerTimeEnd, logStatus);
	
	// package result
	Map<String, Object> maps = new HashMap<String, Object>();
    maps.put("recordsTotal", list_count);		// 总记录数
    maps.put("recordsFiltered", list_count);	// 过滤后的总记录数
    maps.put("data", list);  					// 分页列表
	return maps;
}
 
Example 9
Source File: ORDER.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
private void storeData(final long tupleId, final List<String> currentRow, final int column)
    throws ParseException {

  final String stringValue = currentRow.get(column);
  switch (this.types.get(column).getSpecificType()) {
    case DOUBLE:
      final Double doubleValue = (stringValue == null) ? null : Double.valueOf(stringValue);
      this.dataByColumns.get(column).add(new RowIndexedDoubleValue(tupleId, doubleValue));
      break;
    case DATE:
      final Date dateValue =
      (stringValue == null) ? null : DateUtils.parseDate(stringValue,
          TypeInferrer.dateFormats);
      this.dataByColumns.get(column).add(new RowIndexedDateValue(tupleId, dateValue));
      break;
    case LONG:
      final Long longValue = (stringValue == null) ? null : Long.valueOf(stringValue);
      this.dataByColumns.get(column).add(new RowIndexedLongValue(tupleId, longValue));
      break;
    case STRING:
      this.dataByColumns.get(column).add(new RowIndexedStringValue(tupleId, stringValue));
      break;
    default:
      this.dataByColumns.get(column).add(new RowIndexedStringValue(tupleId, stringValue));
      break;
  }
}
 
Example 10
Source File: TypeInferrer.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
private boolean isDate(final String value) {
  try {
    DateUtils.parseDate(value, TypeInferrer.dateFormats);
  } catch (final ParseException e) {
    // none of the date format patterns in dateFormats could be matched
    return false;
  }
  return true;
}
 
Example 11
Source File: DateTestCase.java    From fountain with Apache License 2.0 5 votes vote down vote up
/**
 * 测试时间
 */
@SuppressWarnings("deprecation")
@Test
public void testString2TimeWithCommon() {
    try {
        Date dt = DateUtils.parseDate("14:30:22", "HH:mm:ss");
        Assert.assertTrue(dt.getHours() == 14);
        Assert.assertTrue(dt.getMinutes() == 30);
        Assert.assertTrue(dt.getSeconds() == 22);
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
}
 
Example 12
Source File: SearchFilter.java    From wenku with MIT License 5 votes vote down vote up
/**
 * searchParams中过滤时间,时间是根据filedName的名字来判断的
 */
public static Object parseValue(String filedName, Object value) {
    try {
        if (filedName.toLowerCase().endsWith("date")) {
            return DateUtils.parseDate((String) value, new String[] { "yyyy-MM-dd" });
        } else if (filedName.toLowerCase().endsWith("time")) { return DateUtils.parseDate((String) value, new String[] { "yyyy-MM-dd HH:mm:ss" }); }
    } catch (ParseException e) {
        throw new RuntimeException("日期格式不正确", e);
    }
    return value;
}
 
Example 13
Source File: JobLogController.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/pageList")
@ResponseBody
public Map<String, Object> pageList(@RequestParam(required = false, defaultValue = "0") Integer start,
                                    @RequestParam(required = false, defaultValue = "10") Integer length,
                                    Integer jobGroup, Integer jobId, Integer logStatus, String filterTime) {

    // parse param
    Date triggerTimeStart = null;
    Date triggerTimeEnd = null;
    if (StringUtils.isNotBlank(filterTime)) {
        String[] temp = filterTime.split(" - ");
        if (temp != null && temp.length == 2) {
            try {
                triggerTimeStart = DateUtils.parseDate(temp[0], new String[]{"yyyy-MM-dd HH:mm:ss"});
                triggerTimeEnd = DateUtils.parseDate(temp[1], new String[]{"yyyy-MM-dd HH:mm:ss"});
            } catch (ParseException e) {
            }
        }
    }

    // page query
    List<XxlJobLog> list = xxlJobLogDao.pageList(start, length, jobGroup, jobId, triggerTimeStart, triggerTimeEnd, logStatus);
    int listCount = xxlJobLogDao.pageListCount(start, length, jobGroup, jobId, triggerTimeStart, triggerTimeEnd, logStatus);

    // package result
    Map<String, Object> maps = new HashMap<String, Object>();
    maps.put("recordsTotal", listCount);        // 总记录数
    maps.put("recordsFiltered", listCount);    // 过滤后的总记录数
    maps.put("data", list);                    // 分页列表
    return maps;
}
 
Example 14
Source File: UtilTest.java    From seed with Apache License 2.0 5 votes vote down vote up
@Test
public void dateUtilTest() throws ParseException {
    Date begin = DateUtils.parseDate("20170808000800", "yyyyMMddHHmmss");
    Date end = DateUtils.parseDate("20170818000800", "yyyyMMddHHmmss");
    System.out.println(DateUtil.getDistanceTime(begin, end));
    System.out.println(DateUtil.getDistanceDay(begin, end));
}
 
Example 15
Source File: DateFormatter.java    From webmagic with Apache License 2.0 4 votes vote down vote up
@Override
public Date format(String raw) throws Exception {
    return DateUtils.parseDate(raw, datePatterns);
}
 
Example 16
Source File: DateTools.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Date floorDate(String year, String month, String day, Integer adjust) throws Exception {
	Date date = DateUtils.parseDate(
			StringUtils.trimToEmpty(year) + StringUtils.trimToEmpty(month) + StringUtils.trimToEmpty(day),
			format_yyyyMMdd, formatCompact_yyyyMMdd);
	return floorDate(date, adjust);
}
 
Example 17
Source File: DateTools.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Date parse(String str) throws Exception {
	return DateUtils.parseDate(str, new String[] { format_yyyyMMddHHmmss, format_yyyyMMdd, format_HHmmss });
}
 
Example 18
Source File: DateTools.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Date ceilDate(String year, String month, String day, Integer adjust) throws Exception {
	Date date = DateUtils.parseDate(
			StringUtils.trimToEmpty(year) + StringUtils.trimToEmpty(month) + StringUtils.trimToEmpty(day),
			format_yyyyMMdd, formatCompact_yyyyMMdd);
	return ceilDate(date, adjust);
}
 
Example 19
Source File: DateUtil.java    From feilong-core with Apache License 2.0 4 votes vote down vote up
/**
 * 将时间字符串 <code>dateString</code> 使用<b>一个或者多个</b>不同的 <code>datePattern</code> 模式按照顺序转换成date类型.
 * 
 * <h3>示例:</h3>
 * 
 * <blockquote>
 * 
 * <pre class="code">
 * DateUtil.toDate("2016-02-33", DatePattern.COMMON_DATE)                   = 2016-03-04
 * DateUtil.toDate("2016-06-28T01:21:12-0800", "yyyy-MM-dd'T'HH:mm:ssZ")    = 2016-06-28 17:21:12
 * DateUtil.toDate("2016-06-28T01:21:12+0800", "yyyy-MM-dd'T'HH:mm:ssZ")    = 2016-06-28 01:21:12
 * </pre>
 * 
 * </blockquote>
 * 
 * <h3>注意:</h3>
 * <blockquote>
 * <ol>
 * <li>转换的时候,使用日历的<b>宽松模式</b>,参见 {@link java.text.DateFormat#setLenient(boolean)},即支持传入"2016-02-33",会转换成 2016-03-04</li>
 * <li>如果能解析所有的字符串,那么视为成功</li>
 * <li>如果没有任何的模式匹配,将会抛出异常</li>
 * <li>如果转换有异常,会将 {@link ParseException} 转成 {@link IllegalArgumentException} 返回,是 UnCheckedException异常 ,不需要强制catch处理</li>
 * </ol>
 * </blockquote>
 * 
 * <h3>示例:</h3>
 * 
 * <blockquote>
 * 
 * 经常我们会看到小伙伴写出下面的代码:
 * 
 * <pre class="code">
 * SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
 * Date publishTimeDate = null;
 * try{
 *     publishTimeDate = format.parse(publishTime);
 * }catch (ParseException e1){
 *     e1.printStackTrace();
 * }
 * </pre>
 * 
 * <p>
 * 可以看到直接使用 {@code SimpleDateFormat} 来写代码的话,代码行数较多,并且还需要自行处理 ParseException checkedException异常, 而且catch里面一般都是写的废话
 * </p>
 * 
 * <p>
 * 此时你可以一行代码搞定:
 * </p>
 * 
 * <pre class="code">
 * 
 * Date publishTimeDate = DateUtil.toDate(publishTime, DatePattern.COMMON_DATE_AND_TIME_WITHOUT_SECOND);
 * </pre>
 * 
 * </blockquote>
 * 
 * @param dateString
 *            时间字符串
 * @param datePatterns
 *            模式,时间字符串的模式{@link DatePattern}
 * @return 如果 <code>dateString</code> 是null,抛出 {@link NullPointerException}<br>
 *         如果 <code>dateString</code> 是blank,抛出 {@link IllegalArgumentException}<br>
 *         如果 <code>datePatterns</code> 是 null,抛出 {@link NullPointerException}<br>
 *         如果 <code>datePatterns</code> 是 empty,抛出 {@link IllegalArgumentException}<br>
 *         如果 <code>datePatterns</code> 有元素是 null,抛出 {@link IllegalArgumentException}<br>
 * @see org.apache.commons.lang3.time.DateUtils#parseDate(String, String...)
 * @see <a href="http://stackoverflow.com/questions/4216745/java-string-to-date-conversion/">java-string-to-date-conversion</a>
 * @see <a href="http://stackoverflow.com/questions/4216745/java-string-to-date-conversion/22180505#22180505">java-string-to-date-
 *      conversion/22180505#22180505</a>
 * @see <a href="http://stackoverflow.com/questions/2735023/convert-string-to-java-util-date">convert-string-to-java-util-date</a>
 * @since 1.7.3 change param to datePatterns array
 */
public static Date toDate(String dateString,String...datePatterns){
    Validate.notBlank(dateString, "dateString can't be blank!");

    Validate.notEmpty(datePatterns, "datePatterns can't be null!");
    Validate.noNullElements(datePatterns, "datePatterns can't has null datePattern");

    //---------------------------------------------------------------

    try{
        return DateUtils.parseDate(dateString, datePatterns);
    }catch (ParseException e){
        String pattern = "dateString:[{}],use patterns:[{}],parse to date exception,message:[{}]";
        throw new IllegalArgumentException(Slf4jUtil.format(pattern, dateString, datePatterns, e.getMessage()), e);
    }
}
 
Example 20
Source File: ParseDate.java    From levelup-java-examples with Apache License 2.0 3 votes vote down vote up
@Test
@Ignore("Build fails due to timezone discrepancy")
public void parse_date_string_in_java_with_apache_commons () throws ParseException {

    String superBowlIIAsString = "January 14, 1968";

	Date superBowlIIAsDate = DateUtils.parseDate(superBowlIIAsString, "MMMM dd, yyyy");

       assertEquals(-62013600000l, superBowlIIAsDate.getTime());
}