List of usage examples for java.text SimpleDateFormat setLenient
public void setLenient(boolean lenient)
From source file:com.ut.healthelink.service.impl.transactionInManagerImpl.java
/** * this method returns the pattern date is in so we can convert it properly and translate into mysql datetime insert format *//*w w w .j a v a 2s . c om*/ public Date convertDate(String input) { // some regular expression String time = "(\\s(([01]?\\d)|(2[0123]))[:](([012345]\\d)|(60))" + "[:](([012345]\\d)|(60)))?"; // with a space before, zero or one time // no check for leap years (Schaltjahr) // and 31.02.2006 will also be correct String day = "(([12]\\d)|(3[01])|(0?[1-9]))"; // 01 up to 31 String month = "((1[012])|(0\\d))"; // 01 up to 12 String year = "\\d{4}"; // define here all date format String date = input.replaceAll("/", "-"); date = date.replaceAll("\\.", "-"); //ArrayList<Pattern> patterns = new ArrayList<Pattern>(); //Pattern pattern1 = Pattern.compile(day + "-" + month + "-" + year + time); //not matching, doesn't work for 01-02-2014 is it jan or feb, will only accept us dates Pattern pattern2 = Pattern.compile(year + "-" + month + "-" + day + time); Pattern pattern3 = Pattern.compile(month + "-" + day + "-" + year + time); // check dates //month needs to have leading 0 if (date.indexOf("-") == 1) { date = "0" + date; } if (pattern2.matcher(date).matches()) { //we have y-m-d format, we transform and return date try { SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-mm-dd"); dateformat.setLenient(false); Date dateValue = dateformat.parse(date); return dateValue; } catch (Exception e) { e.printStackTrace(); return null; } } else if (pattern3.matcher(date).matches()) { //we have m-d-y format, we transform and return date try { SimpleDateFormat dateformat = new SimpleDateFormat("MM-dd-yyyy"); dateformat.setLenient(false); Date dateValue = dateformat.parse(date); return dateValue; } catch (Exception e) { e.printStackTrace(); return null; } } else { return null; } }
From source file:com.jkoolcloud.tnt4j.core.UsecTimestamp.java
/** * <p>Creates UsecTimestamp from string representation of timestamp in the * specified format.</p>/*ww w.j ava2 s .c om*/ * <p>This is based on {@link SimpleDateFormat}, but extends its support to * recognize microsecond fractional seconds. If number of fractional second * characters is greater than 3, then it's assumed to be microseconds. * Otherwise, it's assumed to be milliseconds (as this is the behavior of * {@link SimpleDateFormat}. * * @param timeStampStr timestamp string * @param formatStr format specification for timestamp string * @param timeZone time zone that timeStampStr represents. This is only needed when formatStr does not include * time zone specification and timeStampStr does not represent a string in local time zone. * @param locale locale for date format to use. * @throws NullPointerException if timeStampStr is {@code null} * @throws IllegalArgumentException if timeStampStr is not in the correct format * @throws ParseException if failed to parse string based on specified format * @see java.util.TimeZone */ public UsecTimestamp(String timeStampStr, String formatStr, TimeZone timeZone, String locale) throws ParseException { if (timeStampStr == null) throw new NullPointerException("timeStampStr must be non-null"); int usecs = 0; SimpleDateFormat dateFormat; if (StringUtils.isEmpty(formatStr)) { dateFormat = new SimpleDateFormat(); } else { // Java date formatter cannot deal with usecs, so we need to extract those ourselves int fmtPos = formatStr.indexOf('S'); if (fmtPos > 0) { int endFmtPos = formatStr.lastIndexOf('S'); int fmtFracSecLen = endFmtPos - fmtPos + 1; if (fmtFracSecLen > 6) throw new ParseException( "Date format containing more than 6 significant digits for fractional seconds is not supported", 0); StringBuilder sb = new StringBuilder(); int usecPos = timeStampStr.lastIndexOf('.') + 1; int usecEndPos; if (usecPos > 2) { for (usecEndPos = usecPos; usecEndPos < timeStampStr.length(); usecEndPos++) { if (!StringUtils.containsAny("0123456789", timeStampStr.charAt(usecEndPos))) break; } if (fmtFracSecLen > 3) { // format specification represents more than milliseconds, assume microseconds String usecStr = String.format("%s", timeStampStr.substring(usecPos, usecEndPos)); if (usecStr.length() < fmtFracSecLen) usecStr = StringUtils.rightPad(usecStr, fmtFracSecLen, '0'); else if (usecStr.length() > fmtFracSecLen) usecStr = usecStr.substring(0, fmtFracSecLen); usecs = Integer.parseInt(usecStr); // trim off fractional part < microseconds from both timestamp and format strings sb.append(timeStampStr); sb.delete(usecPos - 1, usecEndPos); timeStampStr = sb.toString(); sb.setLength(0); sb.append(formatStr); sb.delete(fmtPos - 1, endFmtPos + 1); formatStr = sb.toString(); } else if ((usecEndPos - usecPos) < 3) { // pad msec value in date string with 0's so that it is 3 digits long sb.append(timeStampStr); while ((usecEndPos - usecPos) < 3) { sb.insert(usecEndPos, '0'); usecEndPos++; } timeStampStr = sb.toString(); } } } dateFormat = StringUtils.isEmpty(locale) ? new SimpleDateFormat(formatStr) : new SimpleDateFormat(formatStr, Utils.getLocale(locale)); } dateFormat.setLenient(true); if (timeZone != null) dateFormat.setTimeZone(timeZone); Date date = dateFormat.parse(timeStampStr); setTimestampValues(date.getTime(), 0, 0); add(0, usecs); }
From source file:com.aimluck.eip.schedule.util.ScheduleUtils.java
public static boolean setFormDataDelegate(RunData rundata, Context context, ALData formdata, Field[] fields, List<String> msgList) throws ALPageNotFoundException, ALDBErrorException { if (fields == null || fields.length == 0) { return false; }//from ww w . j a va 2 s .co m boolean res = false; try { String FORMAT_DATE = "yyyyMMdd"; String FORMAT_TIME = "HHmm"; int FORMAT_DATE_LEN = FORMAT_DATE.length(); int FORMAT_TIME_LEN = FORMAT_TIME.length(); int length = fields.length; for (int i = 0; i < length; i++) { fields[i].setAccessible(true); String name = fields[i].getName(); Object obj = fields[i].get(formdata); // ? ALCellDateTimeField ?? if (obj instanceof ALCellDateTimeField) { String dateString = new StringBuffer().append(name).append("_date").toString(); String timeString = new StringBuffer().append(name).append("_time").toString(); ALCellDateTimeField field = (ALCellDateTimeField) obj; String dateStr = null; String timeStr = null; Calendar cal = Calendar.getInstance(); if (rundata.getParameters().containsKey(dateString)) { dateStr = rundata.getParameters().getString(dateString); } else { continue; } if (rundata.getParameters().containsKey(timeString)) { timeStr = rundata.getParameters().getString(timeString); } else { continue; } if (dateStr.length() != FORMAT_DATE_LEN) { // ????????? msgList.add(ALLocalizationUtils.getl10n("SCHEDULE_MESSAGE_NON_DAY")); continue; } if (timeStr.length() != FORMAT_TIME_LEN) { // ????????? msgList.add(ALLocalizationUtils.getl10n("SCHEDULE_MESSAGE_NON_TIME")); continue; } List<String> tmpList = new ArrayList<String>(); ALCellStringField sf = new ALCellStringField(dateStr); sf.setTrim(true); sf.setCharacterType(ALStringField.TYPE_NUMBER); sf.setValue(dateStr); sf.validate(tmpList); if (tmpList.size() != 0) { msgList.add(ALLocalizationUtils.getl10n("SCHEDULE_MESSAGE_NON_DAY")); continue; } sf = new ALCellStringField(timeStr); sf.setTrim(true); sf.setCharacterType(ALStringField.TYPE_NUMBER); sf.setValue(timeStr); sf.validate(tmpList); if (tmpList.size() != 0) { msgList.add(ALLocalizationUtils.getl10n("SCHEDULE_MESSAGE_NON_TIME")); continue; } Date date = null; // ??? SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_DATE); sdf.setLenient(false); sdf.setTimeZone(TimeZone.getDefault()); if (!dateStr.equals("")) { try { date = sdf.parse(dateStr); } catch (Exception e) { msgList.add(ALLocalizationUtils.getl10n("SCHEDULE_MESSAGE_NON_DAY")); continue; } } else { continue; } Date time = null; SimpleDateFormat sdf2 = new SimpleDateFormat(FORMAT_TIME); sdf2.setLenient(false); sdf2.setTimeZone(TimeZone.getDefault()); if (!timeStr.equals("")) { try { time = sdf2.parse(timeStr); } catch (Exception e) { msgList.add(ALLocalizationUtils.getl10n("SCHEDULE_MESSAGE_NON_TIME")); continue; } } else { continue; } Calendar cal2 = Calendar.getInstance(); cal2.setTime(time); cal.setLenient(false); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, cal2.get(Calendar.HOUR_OF_DAY)); cal.set(Calendar.MINUTE, cal2.get(Calendar.MINUTE)); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); field.setValue(cal.getTime()); // ? ALCellDateField ?? } else if (obj instanceof ALCellDateField) { ALCellDateField field = (ALCellDateField) obj; Date date = null; ALDateContainer con = new ALDateContainer(); String dateString = new StringBuffer().append(name).toString(); String dateStr = null; if (rundata.getParameters().containsKey(name)) { dateStr = rundata.getParameters().getString(dateString); } else { continue; } if (dateStr.length() != FORMAT_DATE_LEN) { // ????????? msgList.add(ALLocalizationUtils.getl10n("SCHEDULE_MESSAGE_NON_DAY")); continue; } List<String> tmpList = new ArrayList<String>(); ALCellStringField sf = new ALCellStringField(dateStr); sf.setTrim(true); sf.setCharacterType(ALStringField.TYPE_NUMBER); sf.setValue(dateStr); sf.validate(tmpList); if (tmpList.size() != 0) { msgList.add(ALLocalizationUtils.getl10n("SCHEDULE_MESSAGE_NON_DAY")); continue; } // ??? SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_DATE); sdf.setLenient(false); sdf.setTimeZone(TimeZone.getDefault()); try { date = sdf.parse(dateStr); } catch (Exception e) { msgList.add(ALLocalizationUtils.getl10n("SCHEDULE_MESSAGE_NON_DAY")); continue; } Calendar cal = Calendar.getInstance(); cal.setLenient(false); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); con.setYear(cal.get(Calendar.YEAR)); con.setMonth(cal.get(Calendar.MONTH) + 1); con.setDay(cal.get(Calendar.DATE)); field.setValue(con); // ? ALAbstractField ?? } else if (obj instanceof ALAbstractField) { ALAbstractField field = (ALAbstractField) obj; if (rundata.getParameters().containsKey(name)) { field.setValue(rundata.getParameters().getString(name)); } } } res = true; } catch (RuntimeException e) { logger.error("schedule", e); return false; } catch (Exception ex) { logger.error("schedule", ex); return false; } return res; }
From source file:de.innovationgate.wgpublisher.webtml.utils.TMLContext.java
public Date stringtodate(String text) { if (text == null) { return null; }//from ww w. j a v a 2 s . c o m if (text.indexOf(":") == -1) { text += " 0:00"; } SimpleDateFormat dateFormat = new SimpleDateFormat(); dateFormat.setLenient(true); return dateFormat.parse(text, new ParsePosition(0)); }
From source file:au.org.theark.core.dao.StudyDao.java
private boolean validDateFormat(String value) { String[] formatStrings = { Constants.DD_MM_YYYY }; boolean isInvalidFormat = false; for (String formatString : formatStrings) { try {//from w ww .j a v a 2 s . c o m SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getDateInstance(); sdf.applyPattern(formatString); sdf.setLenient(false); sdf.parse(value); if (sdf.format(sdf.parse(value)).equals(value) && value.length() == sdf.toPattern().length()) { isInvalidFormat = true; } } catch (ParseException e) { isInvalidFormat = false; } } return isInvalidFormat; }
From source file:com.clark.func.Functions.java
/** * <p>// w w w .java 2s . com * Parses a string representing a date by trying a variety of different * parsers. * </p> * * <p> * The parse will try each parse pattern in turn. A parse is only deemed * successful if it parses the whole of the input string. If no parse * patterns match, a ParseException is thrown. * </p> * * @param str * the date to parse, not null * @param parsePatterns * the date format patterns to use, see SimpleDateFormat, not * null * @param lenient * Specify whether or not date/time parsing is to be lenient. * @return the parsed date * @throws IllegalArgumentException * if the date string or pattern array is null * @throws ParseException * if none of the date patterns were suitable * @see java.util.Calender#isLenient() */ private static Date parseDateWithLeniency(String str, String[] parsePatterns, boolean lenient) throws ParseException { if (str == null || parsePatterns == null) { throw new IllegalArgumentException("Date and Patterns must not be null"); } SimpleDateFormat parser = new SimpleDateFormat(); parser.setLenient(lenient); ParsePosition pos = new ParsePosition(0); for (int i = 0; i < parsePatterns.length; i++) { String pattern = parsePatterns[i]; // LANG-530 - need to make sure 'ZZ' output doesn't get passed to // SimpleDateFormat if (parsePatterns[i].endsWith("ZZ")) { pattern = pattern.substring(0, pattern.length() - 1); } parser.applyPattern(pattern); pos.setIndex(0); String str2 = str; // LANG-530 - need to make sure 'ZZ' output doesn't hit // SimpleDateFormat as it will ParseException if (parsePatterns[i].endsWith("ZZ")) { str2 = str.replaceAll("([-+][0-9][0-9]):([0-9][0-9])$", "$1$2"); } Date date = parser.parse(str2, pos); if (date != null && pos.getIndex() == str2.length()) { return date; } } throw new ParseException("Unable to parse the date: " + str, -1); }