Convert val to a datetime.date instance by trying several
    conversion algorithm.
    If it fails it raise a ValueError exception.
345673
def todate(val):
    '''
    '''
    if not val:
        raise ValueError("Value not provided")
    if isinstance(val, datetime):
        return val.date()
    elif isinstance(val, date):
        return val
    else:
        try:
            ival = int(val)
            sval = str(ival)
            if len(sval) == 8:
                return yyyymmdd2date(val)
            elif len(sval) == 5:
                return juldate2date(val)
            else:
                raise ValueError
        except Exception:
            # Try to convert using the parsing algorithm
            try:
                return date_from_string(val).date()
            except Exception:
                raise ValueError("Could not convert %s to date" % val)
1113840
def convert_value(self, v):
        

        def stringify(value):
            if self.encoding is not None:
                encoder = partial(pprint_thing_encoded,
                                  encoding=self.encoding)
            else:
                encoder = pprint_thing
            return encoder(value)

        kind = _ensure_decoded(self.kind)
        meta = _ensure_decoded(self.meta)
        if kind == 'datetime64' or kind == 'datetime':
            if isinstance(v, (int, float)):
                v = stringify(v)
            v = _ensure_decoded(v)
            v = Timestamp(v)
            if v.tz is not None:
                v = v.tz_convert('UTC')
            return TermValue(v, v.value, kind)
        elif kind == 'timedelta64' or kind == 'timedelta':
            v = Timedelta(v, unit='s').value
            return TermValue(int(v), v, kind)
        elif meta == 'category':
            metadata = com.values_from_object(self.metadata)
            result = metadata.searchsorted(v, side='left')

            # result returns 0 if v is first element or if v is not in metadata
            # check that metadata contains v
            if not result and v not in metadata:
                result = -1
            return TermValue(result, result, 'integer')
        elif kind == 'integer':
            v = int(float(v))
            return TermValue(v, v, kind)
        elif kind == 'float':
            v = float(v)
            return TermValue(v, v, kind)
        elif kind == 'bool':
            if isinstance(v, str):
                v = not v.strip().lower() in ['false', 'f', 'no',
                                              'n', 'none', '0',
                                              '[]', '{}', '']
            else:
                v = bool(v)
            return TermValue(v, v, kind)
        elif isinstance(v, str):
            # string quoting
            return TermValue(v, stringify(v), 'string')
        else:
            raise TypeError("Cannot compare {v} of type {typ} to {kind} column"
                            .format(v=v, typ=type(v), kind=kind))
694170
function fromEpoch(val, def) {
    if (!is_1.isValue(val) || !is_1.isNumber(val))
        return to_1.toDefault(null, def);
    return new Date(val);
}
1101116
def parse(input):
    '''
    
    '''
    if isinstance(input, datetime):
        return input
    if isinstance(input, date):
        return date_to_datetime(input)
    if isinstance(input, time):
        return time_to_datetime(input)
    if isinstance(input, (int, float)):
        return timestamp_to_datetime(input)
    if isinstance(input, (str)):
        return string_to_data_time(input)
    return None
344577
def parse_number(val, use_dateutilparser=False):
    
    if use_dateutilparser:
        funcs = [int, float, parse_list_from_string,
                 dateutil.parser.parse, str]
    else:
        funcs = [int, float, parse_list_from_string, str]
    if (val.strip().startswith("'") and val.strip().endswith("'")) or (val.strip().startswith('"') and val.strip().endswith('"')):
        return val[1:-1]
    for f in funcs:
        try:
            return f(val)
        # eat exception
        except (ValueError, UnicodeEncodeError, UnicodeDecodeError) as ve:
            pass
    raise ValueError('Cannot parse number:', val)
1033887
def _type_convert(self, value):
        
        if value is None:
            return value

        try:
            return datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
        except ValueError:
            pass

        try:
            return int(value)
        except ValueError:
            pass

        try:
            return decimal.Decimal(value)
        except decimal.InvalidOperation:
            pass

        return value
222498
def _convert_value(self, value, model_instance, add):
        

        if not value:
            return value

        # Retrieve the default timezone as the default
        tz = get_default_timezone()

        # If populate_from exists, override the default timezone
        if self.populate_from is not None:
            tz = self._get_populate_from(model_instance)

        if is_naive(value):
            value = make_aware(value=value, timezone=tz)

        # Convert the value to a datetime object in the correct timezone. This
        #   insures that we will have the correct date if we are performing a
        #   time override below.
        value = value.astimezone(tz)

        # Do not convert the time to the time override if auto_now or
        #   auto_now_add is set
        if self.time_override is not None and not (
            self.auto_now or (self.auto_now_add and add)
        ):
            # Retrieve the time override
            time_override = self._get_time_override()

            # Convert the value to the date/time with the appropriate timezone
            value = make_aware(
                value=datetime.combine(
                    date=value.date(),
                    time=time_override
                ),
                timezone=tz
            )

        return value
732236
def _date_to_datetime(value):
  
  if not isinstance(value, datetime.date):
    raise TypeError('Cannot convert to datetime expected date value; '
                    'received %s' % value)
  return datetime.datetime(value.year, value.month, value.day)
219655
function coerceDate (value) {
  if (!(value instanceof Date)) {
    // Is this how you raise a 'field error'?
    throw new Error('Field error: value is not an instance of Date')
  }
  if (isNaN(value.getTime())) {
    throw new Error('Field error: value is an invalid Date')
  }
  return value.toJSON()
}
569135
function(val, sendUpdatedEvt) {
	
	   // Don't try to parse a date if there is no date
	   if( val === '' ) {
	      inputEx.DateField.superclass.setValue.call(this, '', sendUpdatedEvt);
	      return;
	   }
	   var str = "";
	   if (val instanceof Date) {
			str = inputEx.DateField.formatDate(val, this.options.dateFormat);
	   } 
		else if(this.options.valueFormat){
			var dateVal = inputEx.DateField.parseWithFormat(val, this.options.valueFormat);
			str = inputEx.DateField.formatDate(dateVal, this.options.dateFormat);
		}
	   // else date must match this.options.dateFormat
	   else {
	     str = val;
	   }
	
	   inputEx.DateField.superclass.setValue.call(this, str, sendUpdatedEvt);
	}
418355
def value_as_date(self):
        ''' 
        '''
        if self.value is None:
            return None
        v1, v2 = self.value
        if isinstance(v1, numbers.Number):
            dt = datetime.utcfromtimestamp(v1 / 1000)
            d1 = date(*dt.timetuple()[:3])
        else:
            d1 = v1
        if isinstance(v2, numbers.Number):
            dt = datetime.utcfromtimestamp(v2 / 1000)
            d2 = date(*dt.timetuple()[:3])
        else:
            d2 = v2
        return d1, d2
942218
public static boolean isISODate(final String val) throws BadDateException {
    try {
      if (val.length() != 8) {
        return false;
      }
      fromISODate(val);
      return true;
    } catch (Throwable t) {
      return false;
    }
  }
317543
def value_to_db(self, value):
        
        assert isinstance(value, datetime.date)
        assert not isinstance(value, datetime.datetime)

        try:
            value = value - datetime.date(year=1970, month=1, day=1)
        except OverflowError:
            raise tldap.exceptions.ValidationError("is too big a date")

        return str(value.days).encode("utf_8")
965560
def to_datetime(arg):
    


    if isinstance(arg, datetime.datetime):
        return arg
    elif arg == 0:
        return datetime.datetime.now()
    elif isinstance(arg, str):
        if arg == "now":
            arg = datetime.datetime.now()
        elif arg == "?":
            arg = datetime.datetime(1970, 1, 1)
        else:
            arg = str2dt(arg)
    elif isinstance(arg, datetime.date):
        arg = date2datetime(arg)
    elif isinstance(arg, (int, float)):
        # Suppose it is a timestamp
        arg = ts2dt(arg)
    else:
        raise TypeError("Wrong type for argument 'arg': {}".format(arg.__class__.__name__))

    return arg
1271968
def timetopythonvalue(time_val):
    ""
    if isinstance(time_val, sequence):
        return map(timetopythonvalue, time_val)
    elif isinstance(time_val, numeric):
        return datetime.datetime(*(time.gmtime(time_val))[:6])
    elif isinstance(time_val, numeric):
        values = []
        try:
            values = map(long, time_val.split(","))
        except:
            pass
        if values:
            return map(timetopythonvalue, values)
    raise ValueError(repr(time_val))
94390
def _parse_date(self, dt, fmt=None):
        
        try:
            # test if it's not a datelike instance ...
            _dt = utils.Date(dt, fmt=fmt)
        except ValueError:
            # nope, not a datelike instance
            _dt = None
        return _dt
625059
function parse (val) {
  assert(exists(val), 'Invalid date: ' + val)
  var date = new Date(val)
  assert(!isNaN(date.valueOf()), 'Invalid date: ' + val)
  return date
}