Java Code Examples for java.text.SimpleDateFormat#setLenient()

The following examples show how to use java.text.SimpleDateFormat#setLenient() . 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: BusinessObjectDataHelper.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a date in a date format from a string format or null if one wasn't specified. The format of the date should match
 * HerdDao.DEFAULT_SINGLE_DAY_DATE_MASK.
 *
 * @param dateString the date as a string
 *
 * @return the date as a date or null if one wasn't specified or the conversion fails
 */
public Date getDateFromString(String dateString)
{
    Date resultDate = null;

    // For strict date parsing, process the date string only if it has the required length.
    if (dateString.length() == AbstractHerdDao.DEFAULT_SINGLE_DAY_DATE_MASK.length())
    {
        // Try to convert the date string to a Date.
        try
        {
            // Use strict parsing to ensure our date is more definitive.
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(AbstractHerdDao.DEFAULT_SINGLE_DAY_DATE_MASK, Locale.US);
            simpleDateFormat.setLenient(false);
            resultDate = simpleDateFormat.parse(dateString);
        }
        catch (ParseException e)
        {
            // This assignment is here to pass PMD checks.
            resultDate = null;
        }
    }

    return resultDate;
}
 
Example 2
Source File: Test.java    From BotLibre with Eclipse Public License 1.0 6 votes vote down vote up
public static void testDates() throws Exception {
	SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd hh mm a");
	f.setLenient(false);
	System.out.println(f.parse("2016-10-11 1 30 pm"));
	/*Calendar calendar = Calendar.getInstance();
	calendar.setTimeZone(TimeZone.getTimeZone("GMT+1"));
	Time time = Utils.parseTime(
			calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE) + ":" + calendar.get(Calendar.SECOND));
	System.out.println(Utils.printTime(time, "hh:mm:ss"));*/

	//System.out.println(new Timestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2016/10-11 12 10:00").getTime()));

	//System.out.println(Http.printDate(Utils.parseTimestamp("2016-10-11 14:00:00")));
	//System.out.println(new GoogleCalendar().printDate(new Date()));

	/*Calendar calendar = Calendar.getInstance();
	System.out.println(calendar.getTimeZone().getOffset(calendar.getTimeInMillis()) / Utils.HOUR);
	System.out.println((int)(calendar.get(Calendar.ZONE_OFFSET) / Utils.HOUR));*/
}
 
Example 3
Source File: ExsltDatetime.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Attempt to parse an input string with the allowed formats, returning
 * null if none of the formats work.
 */
private static Date testFormats (String in, String[] formats)
  throws ParseException
{
  for (int i = 0; i <formats.length; i++)
  {
    try
    {
      SimpleDateFormat dateFormat = new SimpleDateFormat(formats[i]);
      dateFormat.setLenient(false);
      return dateFormat.parse(in);
    }
    catch (ParseException pe)
    {
    }
  }
  return null;
}
 
Example 4
Source File: ExsltDatetime.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the start of zone information if the input ends
 * with 'Z' or +/-hh:mm. If a zone string is not
 * found, return -1; if the zone string is invalid,
 * return -2.
 */
private static int getZoneStart (String datetime)
{
  if (datetime.indexOf("Z") == datetime.length()-1)
    return datetime.length()-1;
  else if (datetime.length() >=6
            && datetime.charAt(datetime.length()-3) == ':'
            && (datetime.charAt(datetime.length()-6) == '+'
                || datetime.charAt(datetime.length()-6) == '-'))
  {
    try
    {
      SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
      dateFormat.setLenient(false);
      Date d = dateFormat.parse(datetime.substring(datetime.length() -5));
      return datetime.length()-6;
    }
    catch (ParseException pe)
    {
      System.out.println("ParseException " + pe.getErrorOffset());
      return -2; // Invalid.
    }

  }
    return -1; // No zone information.
}
 
Example 5
Source File: ExsltDatetime.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Attempt to parse an input string with the allowed formats, returning
 * null if none of the formats work.
 */
private static Date testFormats (String in, String[] formats)
  throws ParseException
{
  for (int i = 0; i <formats.length; i++)
  {
    try
    {
      SimpleDateFormat dateFormat = new SimpleDateFormat(formats[i]);
      dateFormat.setLenient(false);
      return dateFormat.parse(in);
    }
    catch (ParseException pe)
    {
    }
  }
  return null;
}
 
Example 6
Source File: ExsltDatetime.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the start of zone information if the input ends
 * with 'Z' or +/-hh:mm. If a zone string is not
 * found, return -1; if the zone string is invalid,
 * return -2.
 */
private static int getZoneStart (String datetime)
{
  if (datetime.indexOf("Z") == datetime.length()-1)
    return datetime.length()-1;
  else if (datetime.length() >=6
            && datetime.charAt(datetime.length()-3) == ':'
            && (datetime.charAt(datetime.length()-6) == '+'
                || datetime.charAt(datetime.length()-6) == '-'))
  {
    try
    {
      SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
      dateFormat.setLenient(false);
      Date d = dateFormat.parse(datetime.substring(datetime.length() -5));
      return datetime.length()-6;
    }
    catch (ParseException pe)
    {
      System.out.println("ParseException " + pe.getErrorOffset());
      return -2; // Invalid.
    }

  }
    return -1; // No zone information.
}
 
Example 7
Source File: ExsltDatetime.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * Attempt to parse an input string with the allowed formats, returning
 * null if none of the formats work.
 */
private static Date testFormats (String in, String[] formats)
  throws ParseException
{
  for (int i = 0; i <formats.length; i++)
  {
    try
    {
      SimpleDateFormat dateFormat = new SimpleDateFormat(formats[i]);
      dateFormat.setLenient(false);
      return dateFormat.parse(in);
    }
    catch (ParseException pe)
    {
    }
  }
  return null;
}
 
Example 8
Source File: AbstractController.java    From nfscan with MIT License 5 votes vote down vote up
/**
 * Initiates the data binding from web request parameters to JavaBeans objects
 *
 * @param webDataBinder - a Web Data Binder instance
 */
@InitBinder
public void initBinder(WebDataBinder webDataBinder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
    dateFormat.setLenient(true);
    webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
 
Example 9
Source File: XmlInputFieldsImportProgressDialog.java    From hop with Apache License 2.0 5 votes vote down vote up
private boolean IsDate( String str ) {
  // TODO: What about other dates? Maybe something for a CRQ
  try {
    SimpleDateFormat fdate = new SimpleDateFormat( "yyyy/MM/dd" );
    fdate.setLenient( false );
    fdate.parse( str );
  } catch ( Exception e ) {
    return false;
  }
  return true;
}
 
Example 10
Source File: Currency.java    From Java8CN with Apache License 2.0 5 votes vote down vote up
private static boolean isPastCutoverDate(String s) throws ParseException {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ROOT);
    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    format.setLenient(false);
    long time = format.parse(s.trim()).getTime();
    return System.currentTimeMillis() > time;

}
 
Example 11
Source File: DateUtil.java    From megatron-java with Apache License 2.0 5 votes vote down vote up
/**
 * Parses specified date string according to format.
 *
 * @param format format pattern, e.g. DATE_TIME_FORMAT_WITH_SECONDS.
 * @param dateStr string to parse.
 */
public static Date parseDateTime(String format, String dateStr) throws ParseException {
    if ((format == null) || (dateStr == null)) {
        return null;
    }

    SimpleDateFormat formatter = new SimpleDateFormat(format);
    formatter.setLenient(false);
    return formatter.parse(dateStr);
}
 
Example 12
Source File: Validators.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
/**
 * Date型に変換します。
 * @param suspect オブジェクト
 * @param pattern 日付の書式
 * @param throwing trueのときに例外をスローします
 * @return 日付型
 */
public static Date toDate(CharSequence suspect, String pattern, boolean throwing) {
    Date value = null;
    try {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        sdf.setLenient(false);
        value = sdf.parse(suspect.toString());
    } catch (ParseException e) {
        L.debug("指定された値({})が日付形式ではありません。日付形式で指定してください", new Object[]{suspect});
        if (throwing) {
            throw new IllegalArgumentException(e);
        }
    }
    return value;
}
 
Example 13
Source File: HttpCookie.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private long expiryDate2DeltaSeconds(String dateString) {
    Calendar cal = new GregorianCalendar(GMT);
    for (int i = 0; i < COOKIE_DATE_FORMATS.length; i++) {
        SimpleDateFormat df = new SimpleDateFormat(COOKIE_DATE_FORMATS[i],
                                                   Locale.US);
        cal.set(1970, 0, 1, 0, 0, 0);
        df.setTimeZone(GMT);
        df.setLenient(false);
        df.set2DigitYearStart(cal.getTime());
        try {
            cal.setTime(df.parse(dateString));
            if (!COOKIE_DATE_FORMATS[i].contains("yyyy")) {
                // 2-digit years following the standard set
                // out it rfc 6265
                int year = cal.get(Calendar.YEAR);
                year %= 100;
                if (year < 70) {
                    year += 2000;
                } else {
                    year += 1900;
                }
                cal.set(Calendar.YEAR, year);
            }
            return (cal.getTimeInMillis() - whenCreated) / 1000;
        } catch (Exception e) {
            // Ignore, try the next date format
        }
    }
    return 0;
}
 
Example 14
Source File: StringUtilsBasic.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 判断字符串是否为日期
 * @param str
 * 			要判断的字符串
 * @param format
 * 			日期格式,按该格式检查字符串
 * @return boolean
 * 			符合为true,不符合为false
 */
public static boolean isDate(String str, String format) {
	if (hasLength(str)) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		formatter.setLenient(false);
		try {
			formatter.format(formatter.parse(str));
		} catch (Exception e) {
			return false;
		}
		return true;
	}
	return false;
}
 
Example 15
Source File: CommonUtils.java    From PhrackCTF-Platform-Personal with Apache License 2.0 4 votes vote down vote up
public static boolean isValidDate(String str) {	
	boolean convertSuccess=true;
	// 指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;


	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	try {
		// 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01


		format.setLenient(false);
		format.parse(str);
	} catch (ParseException e) {
		// e.printStackTrace();


		// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对


		convertSuccess=false;
	} 
	return convertSuccess;
}
 
Example 16
Source File: Portlet20AnnotationControllerTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@InitBinder
private void initBinder(WebDataBinder binder) {
	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	dateFormat.setLenient(false);
	binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
 
Example 17
Source File: DateConverter.java    From gemfirexd-oss with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a converter that uses a {@link SimpleDateFormat} with the given date/time pattern.  The date formatter
 * created is not {@link SimpleDateFormat#setLenient(boolean) lenient}.
 *
 * @param pattern expected date/time pattern
 * @return the new converter
 * @throws NullPointerException if {@code pattern} is {@code null}
 * @throws IllegalArgumentException if {@code pattern} is invalid
 */
public static DateConverter datePattern( String pattern ) {
    SimpleDateFormat formatter = new SimpleDateFormat( pattern );
    formatter.setLenient( false );

    return new DateConverter( formatter );
}
 
Example 18
Source File: DependenciesPostProcessingLov.java    From Knowage-Server with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * Converts a String representing a date into a Date object, given the date format.
 *
 * @param dateStr
 *            The String representing the date
 * @param format
 *            The date format
 *
 * @return the relevant Date object
 *
 * @throws Exception
 *             if any parsing exception occurs
 */
public static Date toDate(String dateStr, String format) throws Exception {
	SimpleDateFormat dateFormat = new SimpleDateFormat();
	Date date = null;
	try {
		dateFormat.applyPattern(format);
		dateFormat.setLenient(false);
		date = dateFormat.parse(dateStr);
	} catch (Exception e) {
		throw e;
	}
	return date;
}
 
Example 19
Source File: SnapshotVersion.java    From helper with MIT License 2 votes vote down vote up
/**
 * Retrieve the snapshot date parser.
 * <p>
 * We have to create a new instance of SimpleDateFormat every time as it is not thread safe.
 * @return The date formatter.
 */
private static SimpleDateFormat getDateFormat() {
    SimpleDateFormat format = new SimpleDateFormat("yy'w'ww", Locale.US);
    format.setLenient(false);
    return format;
}
 
Example 20
Source File: DateConvert.java    From oodt with Apache License 2.0 1 votes vote down vote up
/**
	Parse the given date/time string in timestamp format
	and return the resulting <code>Date</code> object.

	The format is as follows: "yyyyMMddHHmmssSSS".

	@param inputString The string to be parsed.
	@return The resulting Date object.
	@throws ParseException If the string does not match the date/time
	format.
*/
public static Date tsParse(String inputString) throws ParseException {

	// Setup the date format and parse the given string.
	SimpleDateFormat dateFormat = new SimpleDateFormat(TS_FORMAT);
	dateFormat.setLenient(false);

  return(dateFormat.parse(inputString));
}