parse a string to a Datetime Object, returns null if can't convert

@param locale
@param str String representation of a locale Date
@param tz
@param defaultValue
@return datetime object
16018
public static DateTime toDateTime(Locale locale, String str, TimeZone tz, DateTime defaultValue, boolean useCommomDateParserAsWell) {
	str = str.trim();
	tz = ThreadLocalPageContext.getTimeZone(tz);
	DateFormat[] df;

	// get Calendar
	Calendar c = JREDateTimeUtil.getThreadCalendar(locale, tz);

	// datetime
	ParsePosition pp = new ParsePosition(0);
	df = FormatUtil.getDateTimeFormats(locale, tz, false);// dfc[FORMATS_DATE_TIME];
	Date d;
	for (int i = 0; i < df.length; i++) {
	    SimpleDateFormat sdf = (SimpleDateFormat) df[i];
	    // print.e(sdf.format(new Date(108,3,6,1,2,1)) + " : "+sdf.toPattern());
	    pp.setErrorIndex(-1);
	    pp.setIndex(0);
	    sdf.setTimeZone(tz);
	    d = sdf.parse(str, pp);
	    if (pp.getIndex() == 0 || d == null || pp.getIndex() < str.length()) continue;

	    optimzeDate(c, tz, d);
	    return new DateTimeImpl(c.getTime());
	}

	// date
	df = FormatUtil.getDateFormats(locale, tz, false);
	for (int i = 0; i < df.length; i++) {
	    SimpleDateFormat sdf = (SimpleDateFormat) df[i];
	    // print.e(sdf.format(new Date(108,3,6,1,2,1)) + " : "+sdf.toPattern());
	    pp.setErrorIndex(-1);
	    pp.setIndex(0);
	    sdf.setTimeZone(tz);
	    d = sdf.parse(str, pp);
	    if (pp.getIndex() == 0 || d == null || pp.getIndex() < str.length()) continue;
	    optimzeDate(c, tz, d);
	    return new DateTimeImpl(c.getTime());
	}

	// time
	df = FormatUtil.getTimeFormats(locale, tz, false);// dfc[FORMATS_TIME];
	for (int i = 0; i < df.length; i++) {
	    SimpleDateFormat sdf = (SimpleDateFormat) df[i];
	    // print.e(sdf.format(new Date(108,3,6,1,2,1))+ " : "+sdf.toPattern());
	    pp.setErrorIndex(-1);
	    pp.setIndex(0);
	    sdf.setTimeZone(tz);
	    d = sdf.parse(str, pp);
	    if (pp.getIndex() == 0 || d == null || pp.getIndex() < str.length()) continue;
	    c.setTimeZone(tz);
	    c.setTime(d);
	    c.set(Calendar.YEAR, 1899);
	    c.set(Calendar.MONTH, 11);
	    c.set(Calendar.DAY_OF_MONTH, 30);
	    c.setTimeZone(tz);
	    return new DateTimeImpl(c.getTime());
	}

	if (useCommomDateParserAsWell) return DateCaster.toDateSimple(str, CONVERTING_TYPE_NONE, true, tz, defaultValue);
	return defaultValue;
    }
1263304
def convert_timezone(date_str, tz_from, tz_to="UTC", fmt=None):
    
    tz_offset = datetime_to_timezone(
        datetime.datetime.now(), tz=tz_from).strftime('%z')
    tz_offset = tz_offset[:3] + ':' + tz_offset[3:]

    date = parse_date(str(date_str) + tz_offset)
    if tz_from != tz_to:
        date = datetime_to_timezone(date, tz_to)

    if isinstance(fmt, str):
        return date.strftime(fmt)
    return date
503546
static private final Date parseISODate(String stringValue)
  {
    try
    {
      return getDateFormat().parse(stringValue);
    }
    catch (ParseException pe)
    {
      if (LOG.isLoggable(Level.INFO))
      {
        LOG.log(Level.INFO, "CANNOT_PARSE_VALUE_INTO_DATE_WITH_YYYY_MM_DD_PATTERN "+ stringValue, pe);
      }
      return null;
    }
  }
648080
public static Long toTimestamp(String dateStr, TimeZone tz) {
		int length = dateStr.length();
		String format;
		if (length == 21) {
			format = DEFAULT_DATETIME_FORMATS[1];
		} else if (length == 22) {
			format = DEFAULT_DATETIME_FORMATS[2];
		} else if (length == 23) {
			format = DEFAULT_DATETIME_FORMATS[3];
		} else {
			// otherwise fall back to the default
			format = DEFAULT_DATETIME_FORMATS[0];
		}
		return toTimestamp(dateStr, format, tz);
	}
703150
public Date parseDateTime( String str ) throws java.text.ParseException
  {
    if( str == null )
    {
      return null;
    }

    return DateFormat.getDateInstance().parse(str);
  }
599003
def get_date(context, value):
    
    if not value:
        return None
    if isinstance(value, DateTime):
        return value
    if isinstance(value, datetime):
        return dt2DT(value)
    if not isinstance(value, basestring):
        return None

    def try_parse(date_string, format):
        if not format:
            return None
        try:
            struct_time = strptime(date_string, format)
            return datetime(*struct_time[:6])
        except ValueError:
            pass
        return None

    def get_locale_format(key, context):
        format = context.translate(key, domain="senaite.core", mapping={})
        # TODO: Is this replacement below strictly necessary?
        return format.replace(r"${", '%').replace('}', '')

    # Try with prioritized formats
    formats = [get_locale_format("date_format_long", context),
               get_locale_format("date_format_short", context),
               "%Y-%m-%d %H:%M", "%Y-%m-%d", "%Y-%m-%d %H:%M:%S"]
    for pri_format in formats:
        val = try_parse(value, pri_format)
        if not val:
            continue
        val = dt2DT(val)
        if val.timezoneNaive():
            # Use local timezone for tz naive strings
            # see http://dev.plone.org/plone/ticket/10141
            zone = val.localZone(safelocaltime(val.timeTime()))
            parts = val.parts()[:-1] + (zone,)
            val = DateTime(*parts)
        return val

    logger.warn("Unable to convert {} to datetime".format(value))
    return None
760114
@SuppressWarnings("unused")
  public static Date fromISODateTimeUTC(final String val,
                                        final TimeZone tz) throws BadDateException {
    try {
      synchronized (isoDateTimeUTCTZFormat) {
        isoDateTimeUTCTZFormat.setTimeZone(tz);
        return isoDateTimeUTCTZFormat.parse(val);
      }
    } catch (Throwable t) {
      throw new BadDateException();
    }
  }
790455
public static DateTimeValue parse(Calendar cal, DateTimeType type) {

		int sYear = 0;
		int sMonthDay = 0;
		int sTime = 0;
		int sFractionalSecs = 0;
		boolean sPresenceTimezone = false;
		int sTimezone;

		switch (type) {
		case gYear: // gYear Year, [Time-Zone]
		case gYearMonth: // gYearMonth Year, MonthDay, [TimeZone]
		case date: // date Year, MonthDay, [TimeZone]
			sYear = cal.get(Calendar.YEAR);
			sMonthDay = getMonthDay(cal);
			break;
		case dateTime: // dateTime Year, MonthDay, Time, [FractionalSecs],
			// [TimeZone]
			sYear = cal.get(Calendar.YEAR);
			sMonthDay = getMonthDay(cal);
			// Note: *no* break;
		case time: // time Time, [FractionalSecs], [TimeZone]
			sTime = getTime(cal);
			sFractionalSecs = cal.get(Calendar.MILLISECOND);
			break;
		case gMonth: // gMonth MonthDay, [TimeZone]
		case gMonthDay: // gMonthDay MonthDay, [TimeZone]
		case gDay: // gDay MonthDay, [TimeZone]
			sMonthDay = getMonthDay(cal);
			break;
		default:
			throw new UnsupportedOperationException();
		}
		// [TimeZone]
		sTimezone = getTimeZoneInMinutesOffset(cal);
		if (sTimezone != 0) {
			sPresenceTimezone = true;
		}

		return new DateTimeValue(type, sYear, sMonthDay, sTime,
				sFractionalSecs, sPresenceTimezone, sTimezone);
	}
106840
@CheckForNull
  public static Date parseDateOrDateTime(@Nullable String stringDate) {
    if (stringDate == null) {
      return null;
    }

    OffsetDateTime odt = parseOffsetDateTimeQuietly(stringDate);
    if (odt != null) {
      return Date.from(odt.toInstant());
    }

    LocalDate ld = parseLocalDateQuietly(stringDate);
    checkArgument(ld != null, "Date '%s' cannot be parsed as either a date or date+time", stringDate);

    return Date.from(ld.atStartOfDay(ZoneId.systemDefault()).toInstant());
  }
407399
public static String dateFormat(String dateStr, String fromFormat, String toFormat, TimeZone tz) {
		SimpleDateFormat fromFormatter = FORMATTER_CACHE.get(fromFormat);
		fromFormatter.setTimeZone(tz);
		SimpleDateFormat toFormatter = FORMATTER_CACHE.get(toFormat);
		toFormatter.setTimeZone(tz);
		try {
			return toFormatter.format(fromFormatter.parse(dateStr));
		} catch (ParseException e) {
			LOG.error("Exception when formatting: '" + dateStr +
				"' from: '" + fromFormat + "' to: '" + toFormat + "'", e);
			return null;
		}
	}
1231150
public static MonthDay parse(String str, DateTimeFormatter formatter) {
        LocalDate date = formatter.parseLocalDate(str);
        return new MonthDay(date.getMonthOfYear(), date.getDayOfMonth());
    }
908989
public static Object valueFromString(String str, Type type)
    {
        if (str == null || str.isEmpty()) {
            return null;
        }
        else if (Types.isArrayType(type)) {
            Type elementType = Types.getElementType(type);
            ImmutableList.Builder<Object> listBuilder = ImmutableList.builder();
            for (String element : Splitter.on(',').split(str)) {
                listBuilder.add(valueFromString(element, elementType));
            }
            return AccumuloRowSerializer.getBlockFromArray(elementType, listBuilder.build());
        }
        else if (Types.isMapType(type)) {
            Type keyType = Types.getKeyType(type);
            Type valueType = Types.getValueType(type);
            ImmutableMap.Builder<Object, Object> mapBuilder = ImmutableMap.builder();
            for (String element : Splitter.on(',').split(str)) {
                ImmutableList.Builder<String> builder = ImmutableList.builder();
                List<String> keyValue = builder.addAll(Splitter.on("->").split(element)).build();
                checkArgument(keyValue.size() == 2, format("Map element %s has %d entries, not 2", element, keyValue.size()));

                mapBuilder.put(valueFromString(keyValue.get(0), keyType), valueFromString(keyValue.get(1), valueType));
            }
            return AccumuloRowSerializer.getBlockFromMap(type, mapBuilder.build());
        }
        else if (type.equals(BIGINT)) {
            return Long.parseLong(str);
        }
        else if (type.equals(BOOLEAN)) {
            return Boolean.parseBoolean(str);
        }
        else if (type.equals(DATE)) {
            return new Date(DATE_PARSER.parseDateTime(str).getMillis());
        }
        else if (type.equals(DOUBLE)) {
            return Double.parseDouble(str);
        }
        else if (type.equals(INTEGER)) {
            return Integer.parseInt(str);
        }
        else if (type.equals(REAL)) {
            return Float.parseFloat(str);
        }
        else if (type.equals(SMALLINT)) {
            return Short.parseShort(str);
        }
        else if (type.equals(TIME)) {
            return new Time(TIME_PARSER.parseDateTime(str).getMillis());
        }
        else if (type.equals(TIMESTAMP)) {
            return new Timestamp(TIMESTAMP_PARSER.parseDateTime(str).getMillis());
        }
        else if (type.equals(TINYINT)) {
            return Byte.valueOf(str);
        }
        else if (type.equals(VARBINARY)) {
            return str.getBytes(UTF_8);
        }
        else if (type instanceof VarcharType) {
            return str;
        }
        else {
            throw new PrestoException(NOT_SUPPORTED, "Unsupported type " + type);
        }
    }
1374815
def _convert(value, tzto, defaulttz):
    """"""
    if not isinstance(value, datetime):
        raise ValueError('value must be a datetime.datetime object')

    if value.tzinfo is None:
        value = value.replace(tzinfo=defaulttz)

    return value.astimezone(tzto)
42996
public static YearMonth parse(String str, DateTimeFormatter formatter) {
        LocalDate date = formatter.parseLocalDate(str);
        return new YearMonth(date.getYear(), date.getMonthOfYear());
    }
230978
function defaultParse(str) {
  if (typeof str !== 'string') {
    return undefined;
  }
  var split = str.split('-');
  if (split.length !== 3) {
    return undefined;
  }
  var year = parseInt(split[0], 10);
  var month = parseInt(split[1], 10) - 1;
  var day = parseInt(split[2], 10);
  if (isNaN(year) || String(year).length > 4 || isNaN(month) || isNaN(day) || day <= 0 || day > 31 || month < 0 || month >= 12) {
    return undefined;
  }

  return new Date(year, month, day);
}
845728
public static PeriodValue parsePeriodValue(String s, TimeZone tzid)
            throws ParseException {
        int sep = s.indexOf('/');
        if (sep < 0) {
            throw new ParseException(s, s.length());
        }
        DateValue start = parseDateValue(s.substring(0, sep), tzid),
                end = parseDateValue(s.substring(sep + 1), tzid);
        if ((start instanceof TimeValue) != (end instanceof TimeValue)) {
            throw new ParseException(s, 0);
        }
        try {
            return PeriodValueImpl.create(start, end);
        } catch (IllegalArgumentException ex) {
            throw (ParseException) new ParseException(s, sep + 1).initCause(ex);
        }
    }
139885
public static Date parseDate(String datetimeStr) {
        if (StringUtils.isEmpty(datetimeStr)) {
            return null;
        }
        datetimeStr = datetimeStr.trim();
        if (datetimeStr.contains("-")) {
            if (datetimeStr.contains(":")) {
                datetimeStr = datetimeStr.replace(" ", "T");
            }
        } else if (datetimeStr.contains(":")) {
            datetimeStr = "T" + datetimeStr;
        }

        DateTime dateTime = new DateTime(datetimeStr, dateTimeZone);

        return dateTime.toDate();
    }