Preprocess the date string to remove extra whitespace and convert ad hoc
 formatting to equivalent EDTF.

 @todo should '-` be intepreted as 'x' or '?'
 @see http://www.loc.gov/standards/datetime/pre-submission.html#maskedprecision
762305
def preprocess(str)
      str.gsub!(/late/i, '')
      str.gsub!(/early/i, '')
      str.strip!
      str.gsub!(/\s+/, ' ')
      str.gsub!('0s', 'x') if str.match(/^[1-9]+0s$/)
      str.gsub!('-', 'x') if str.match(/^[1-9]+\-+$/)
      str
    end
792092
function formatDate( date ) {

	var dateString = '';

	date = new Date( date );

	dateString = date.getMonth() + 1;
	dateString += '/';
	dateString += date.getDate();
	dateString += '/';
	dateString += date.getFullYear();

	return dateString;
}
279106
def _initPatterns(ptc):
    
    # TODO add code to parse the date formats and build the regexes up from sub-parts
    # TODO find all hard-coded uses of date/time seperators

    ptc.RE_DATE4     = r'''(?P<date>(((?P<day>\d\d?)(?P<suffix>%(daysuffix)s)?(,)?(\s)?)
                                      (?P<mthname>(%(months)s|%(shortmonths)s))\s?
                                      (?P<year>\d\d(\d\d)?)?
                                    )
                           )''' % ptc.re_values

    # I refactored DATE3 to fix Issue 16 http://code.google.com/p/parsedatetime/issues/detail?id=16
    # I suspect the final line was for a trailing time - but testing shows it's not needed
    # ptc.RE_DATE3     = r'''(?P<date>((?P<mthname>(%(months)s|%(shortmonths)s))\s?
    #                                  ((?P<day>\d\d?)(\s?|%(daysuffix)s|$)+)?
    #                                  (,\s?(?P<year>\d\d(\d\d)?))?))
    #                        (\s?|$|[^0-9a-zA-Z])''' % ptc.re_values
    ptc.RE_DATE3     = r'''(?P<date>(
                                     (((?P<mthname>(%(months)s|%(shortmonths)s))|
                                     ((?P<day>\d\d?)(?P<suffix>%(daysuffix)s)?))(\s)?){1,2}
                                     ((,)?(\s)?(?P<year>\d\d(\d\d)?))?
                                    )
                           )''' % ptc.re_values
    ptc.RE_MONTH     = r'''(\s?|^)
                           (?P<month>(
                                      (?P<mthname>(%(months)s|%(shortmonths)s))
                                      (\s?(?P<year>(\d\d\d\d)))?
                                     ))
                           (\s?|$|[^0-9a-zA-Z])''' % ptc.re_values
    ptc.RE_WEEKDAY   = r'''(\s?|^)
                           (?P<weekday>(%(days)s|%(shortdays)s))
                           (\s?|$|[^0-9a-zA-Z])''' % ptc.re_values

    ptc.RE_SPECIAL   = r'(?P<special>^[%(specials)s]+)\s+' % ptc.re_values
    ptc.RE_UNITS     = r'''(?P<qty>(-?\d+\s*
                                    (?P<units>((%(units)s)s?))
                                   ))''' % ptc.re_values
    ptc.RE_QUNITS    = r'''(?P<qty>(-?\d+\s?
                                    (?P<qunits>%(qunits)s)
                                    (\s?|,|$)
                                   ))''' % ptc.re_values
    ptc.RE_MODIFIER  = r'''(\s?|^)
                           (?P<modifier>
                            (previous|prev|last|next|eod|eo|(end\sof)|(in\sa)))''' % ptc.re_values
    ptc.RE_MODIFIER2 = r'''(\s?|^)
                           (?P<modifier>
                            (from|before|after|ago|prior))
                           (\s?|$|[^0-9a-zA-Z])''' % ptc.re_values
    ptc.RE_TIMEHMS   = r'''(\s?|^)
                           (?P<hours>\d\d?)
                           (?P<tsep>%(timeseperator)s|)
                           (?P<minutes>\d\d)
                           (?:(?P=tsep)(?P<seconds>\d\d(?:[.,]\d+)?))?''' % ptc.re_values
    ptc.RE_TIMEHMS2  = r'''(?P<hours>(\d\d?))
                           ((?P<tsep>%(timeseperator)s|)
                            (?P<minutes>(\d\d?))
                            (?:(?P=tsep)
                               (?P<seconds>\d\d?
                                (?:[.,]\d+)?))?)?''' % ptc.re_values

    if 'meridian' in ptc.re_values:
        ptc.RE_TIMEHMS2 += r'\s?(?P<meridian>(%(meridian)s))' % ptc.re_values

    dateSeps = ''.join(ptc.dateSep) + '.'

    ptc.RE_DATE      = r'''(\s?|^)
                           (?P<date>(\d\d?[%s]\d\d?([%s]\d\d(\d\d)?)?))
                           (\s?|$|[^0-9a-zA-Z])''' % (dateSeps, dateSeps)
    ptc.RE_DATE2     = r'[%s]' % dateSeps
    ptc.RE_DAY       = r'''(\s?|^)
                           (?P<day>(today|tomorrow|yesterday))
                           (\s?|$|[^0-9a-zA-Z])''' % ptc.re_values
    ptc.RE_DAY2      = r'''(?P<day>\d\d?)|(?P<suffix>%(daysuffix)s)
                        ''' % ptc.re_values
    ptc.RE_TIME      = r'''(\s?|^)
                           (?P<time>(morning|breakfast|noon|lunch|evening|midnight|tonight|dinner|night|now))
                           (\s?|$|[^0-9a-zA-Z])''' % ptc.re_values
    ptc.RE_REMAINING = r'\s+'

    # Regex for date/time ranges
    ptc.RE_RTIMEHMS  = r'''(\s?|^)
                           (\d\d?)%(timeseperator)s
                           (\d\d)
                           (%(timeseperator)s(\d\d))?
                           (\s?|$)''' % ptc.re_values
    ptc.RE_RTIMEHMS2 = r'''(\s?|^)
                           (\d\d?)
                           (%(timeseperator)s(\d\d?))?
                           (%(timeseperator)s(\d\d?))?''' % ptc.re_values

    if 'meridian' in ptc.re_values:
        ptc.RE_RTIMEHMS2 += r'\s?(%(meridian)s)' % ptc.re_values

    ptc.RE_RDATE  = r'(\d+([%s]\d+)+)' % dateSeps
    ptc.RE_RDATE3 = r'''((((%(months)s))\s?
                         ((\d\d?)
                          (\s?|%(daysuffix)s|$)+)?
                         (,\s?\d\d\d\d)?))''' % ptc.re_values

    # "06/07/06 - 08/09/06"
    ptc.DATERNG1 = ptc.RE_RDATE + r'\s?%(rangeseperator)s\s?' + ptc.RE_RDATE
    ptc.DATERNG1 = ptc.DATERNG1 % ptc.re_values

    # "march 31 - june 1st, 2006"
    ptc.DATERNG2 = ptc.RE_RDATE3 + r'\s?%(rangeseperator)s\s?' + ptc.RE_RDATE3
    ptc.DATERNG2 = ptc.DATERNG2 % ptc.re_values

    # "march 1rd -13th"
    ptc.DATERNG3 = ptc.RE_RDATE3 + r'\s?%(rangeseperator)s\s?(\d\d?)\s?(rd|st|nd|th)?'
    ptc.DATERNG3 = ptc.DATERNG3 % ptc.re_values

    # "4:00:55 pm - 5:90:44 am", '4p-5p'
    ptc.TIMERNG1 = ptc.RE_RTIMEHMS2 + r'\s?%(rangeseperator)s\s?' + ptc.RE_RTIMEHMS2
    ptc.TIMERNG1 = ptc.TIMERNG1 % ptc.re_values

    # "4:00 - 5:90 ", "4:55:55-3:44:55"
    ptc.TIMERNG2 = ptc.RE_RTIMEHMS + r'\s?%(rangeseperator)s\s?' + ptc.RE_RTIMEHMS
    ptc.TIMERNG2 = ptc.TIMERNG2 % ptc.re_values

    # "4-5pm "
    ptc.TIMERNG3 = r'\d\d?\s?%(rangeseperator)s\s?' + ptc.RE_RTIMEHMS2
    ptc.TIMERNG3 = ptc.TIMERNG3 % ptc.re_values

    # "4:30-5pm "
    ptc.TIMERNG4 = ptc.RE_RTIMEHMS + r'\s?%(rangeseperator)s\s?' + ptc.RE_RTIMEHMS2
    ptc.TIMERNG4 = ptc.TIMERNG4 % ptc.re_values
280604
def date_to_string(date)
      precision = date.precision
      if CarbonDate::Date::PRECISION.include? precision # Call me paranoid: whitelist the available functions
        public_send(precision, date)
      else
        raise StandardError.new("Unrecognized precision: #{precision}")
      end
    end
915928
public static function standardizeDate($string)
    {
        // Only standardize dates in localized environments
        if (self::isLocalized()) {

            // Translate names to English
            foreach (self::$_datetime_dictionary as $values) {
                $string = preg_replace('/\b' . self::translate($values) . '\b/i' . (self::isUnicodeCompiled() === true ? 'u' : null), $values, $string);
            }

            // Replace custom date and time separator with space:
            // This is important, otherwise the `DateTime` constructor may break
            // @todo Test if this separator is still required. It's a hidden setting
            // and users are only aware of it if they go digging/pointed in the right direction
            $separator = Symphony::Configuration()->get('datetime_separator', 'region');
            if ($separator !== ' ') {
                $string = str_replace($separator, ' ', $string);
            }
        }

        return $string;
    }
299362
function datePrettyFormat(ms, opts) {
  if (typeof ms !== 'number') {
    throw new TypeError('Expected a number');
  }

  if (ms < 1000) {
    return Math.ceil(ms) + 'ms';
  }

  opts = opts || {};

  var secDecimalDigits = typeof opts.secDecimalDigits === 'number' ? opts.secDecimalDigits : 1;
  var ret = [];
  var parsed = formatDate(ms);

  ret = add(ret, parsed.years, 'y');
  ret = add(ret, parsed.days, 'd');
  ret = add(ret, parsed.hours, 'h');
  ret = add(ret, parsed.minutes, 'm');

  if (opts.compact) {
    ret = add(ret, parsed.seconds, 's');
    return '~' + ret[0];
  }

  ret = add(ret, (ms / 1000 % 60).toFixed(secDecimalDigits).replace(/\.0$/, ''), 's');

  return ret.join(' ');
}
911470
private static String cleanDate(final String dateString) {
        if (dateString == null) {
            return dateString;
        }

        String retValue = dateString;
        retValue = THURSDAY_DATE_RE.matcher(retValue).replaceAll("Thu");
        retValue = TUESDAY_DATE_RE.matcher(retValue).replaceAll("Tue");

        return retValue;
    }
1000339
function parseDate(str/*:string|Date*/, fixdate/*:?number*/)/*:Date*/ {
	var d = new Date(str);
	if(good_pd) {
		/*:: if(fixdate == null) fixdate = 0; */
		if(fixdate > 0) d.setTime(d.getTime() + d.getTimezoneOffset() * 60 * 1000);
		else if(fixdate < 0) d.setTime(d.getTime() - d.getTimezoneOffset() * 60 * 1000);
		return d;
	}
	if(str instanceof Date) return str;
	if(good_pd_date.getFullYear() == 1917 && !isNaN(d.getFullYear())) {
		var s = d.getFullYear();
		if(str.indexOf("" + s) > -1) return d;
		d.setFullYear(d.getFullYear() + 100); return d;
	}
	var n = str.match(/\d+/g)||["2017","2","19","0","0","0"];
	var out = new Date(+n[0], +n[1] - 1, +n[2], (+n[3]||0), (+n[4]||0), (+n[5]||0));
	if(str.indexOf("Z") > -1) out = new Date(out.getTime() - out.getTimezoneOffset() * 60 * 1000);
	return out;
}
451125
protected function preprocess() {
		if ( $this->preprocessed || $this->skipPreprocess ) {
			return;
		}

		// Normalize line endings
		if ( strcspn( $this->text, "\r" ) !== strlen( $this->text ) ) {
			$this->text = preg_replace( '/\r\n?/', "\n", $this->text );
			$this->length = strlen( $this->text );
		}

		// Raise parse errors for any control characters
		static $re;
		if ( $re === null ) {
			// Note that we deliberately do not use the 'u' flag on the
			// regexp below, as that bypasses the PCRE JIT.  Instead we
			// rewrite character classes containing codepoints which
			// require more than one UTF-8 byte as alternations.
			$re = '/[' .
				// "C0 controls" (u0000 - u001F) but not
				// "ASCII whitespace" (u0009, u000A, u000C, u000D, u0020) or
				// NULL (u0000)
				// https://infra.spec.whatwg.org/#c0-control
				// https://infra.spec.whatwg.org/#ascii-whitespace
				'\x{0001}-\x{0008}' .
				'\x{000B}' .
				'\x{000E}-\x{001F}' .
				// "Controls" other than C0 controls (u007F - u009F)
				// https://infra.spec.whatwg.org/#control
				'\x{007F}]|' .
				// (We can't use character classes above u007F)
				"\u{0080}|\u{0081}|\u{0082}|\u{0083}|" .
				"\u{0084}|\u{0085}|\u{0086}|\u{0087}|" .
				"\u{0088}|\u{0089}|\u{008A}|\u{008B}|" .
				"\u{008C}|\u{008D}|\u{008E}|\u{008F}|" .
				"\u{0090}|\u{0091}|\u{0092}|\u{0093}|" .
				"\u{0094}|\u{0095}|\u{0096}|\u{0097}|" .
				"\u{0098}|\u{0099}|\u{009A}|\u{009B}|" .
				"\u{009C}|\u{009D}|\u{009E}|\u{009F}|" .
				// HTML spec calls these "noncharacters"
				// https://infra.spec.whatwg.org/#noncharacter
				"\u{FDD0}|\u{FDD1}|\u{FDD2}|\u{FDD3}|" .
				"\u{FDD4}|\u{FDD5}|\u{FDD6}|\u{FDD7}|" .
				"\u{FDD8}|\u{FDD9}|\u{FDDA}|\u{FDDB}|" .
				"\u{FDDC}|\u{FDDD}|\u{FDDE}|\u{FDDF}|" .
				"\u{FDE0}|\u{FDE1}|\u{FDE2}|\u{FDE3}|" .
				"\u{FDE4}|\u{FDE5}|\u{FDE6}|\u{FDE7}|" .
				"\u{FDE8}|\u{FDE9}|\u{FDEA}|\u{FDEB}|" .
				"\u{FDEC}|\u{FDED}|\u{FDEE}|\u{FDEF}|" .
				"\u{FFFE}|\u{FFFF}|" .
				"\u{1FFFE}|\u{1FFFF}|" .
				"\u{2FFFE}|\u{2FFFF}|" .
				"\u{3FFFE}|\u{3FFFF}|" .
				"\u{4FFFE}|\u{4FFFF}|" .
				"\u{5FFFE}|\u{5FFFF}|" .
				"\u{6FFFE}|\u{6FFFF}|" .
				"\u{7FFFE}|\u{7FFFF}|" .
				"\u{8FFFE}|\u{8FFFF}|" .
				"\u{9FFFE}|\u{9FFFF}|" .
				"\u{AFFFE}|\u{AFFFF}|" .
				"\u{BFFFE}|\u{BFFFF}|" .
				"\u{CFFFE}|\u{CFFFF}|" .
				"\u{DFFFE}|\u{DFFFF}|" .
				"\u{EFFFE}|\u{EFFFF}|" .
				"\u{FFFFE}|\u{FFFFF}|" .
				"\u{10FFFE}|\u{10FFFF}/S";
		}
		if ( !$this->ignoreErrors ) {
			$pos = 0;
			while ( $pos < $this->length ) {
				$count = preg_match( $re, $this->text, $m, PREG_OFFSET_CAPTURE, $pos );
				if ( $count === false ) {
					$this->throwPregError();
				} elseif ( !$count ) {
					break;
				}
				$pos = $m[0][1];
				$this->error( "disallowed control character", $pos );
				$pos += strlen( $m[0][0] );
			}
		}
	}
1103458
def dt_from_rfc8601(date_str):
    
    # Normalize string and adjust for milliseconds. Note that Python 2.6+ has
    # ".%f" format, but we're going for Python 2.5, so truncate the portion.
    date_str = date_str.rstrip('Z').split('.')[0]

    # Format string. (2010-04-13T14:02:48.000Z)
    fmt = "%Y-%m-%dT%H:%M:%S"
    # Python 2.6+: Could format and handle milliseconds.
    # if date_str.find('.') >= 0:
    #    fmt += ".%f"

    return datetime.strptime(date_str, fmt)
868427
function( dateString, format ) {

			this.setFormat(format);
			this.clearDate();
			var parts = [];

			// discover timezone separtor for auto profile // default is ':'
			if(dateString.indexOf('-') === -1) {
				this.autoProfile.tsep = '';
			}

			// YYYY-DDD
			parts = dateString.match( /(\d\d\d\d)-(\d\d\d)/ );
			if(parts) {
				if(parts[1]) {
					this.dY = parts[1];
				}
				if(parts[2]) {
					this.dDDD = parts[2];
				}
			}

			if(this.dDDD === -1) {
				// YYYY-MM-DD ie 2008-05-01 and YYYYMMDD ie 20080501
				parts = dateString.match( /(\d\d\d\d)?-?(\d\d)?-?(\d\d)?/ );
				if(parts[1]) {
					this.dY = parts[1];
				}
				if(parts[2]) {
					this.dM = parts[2];
				}
				if(parts[3]) {
					this.dD = parts[3];
				}
			}
			return this.toString(this.format);
		}
655779
function formatDate(date) {
  let timestamp;
  if (date instanceof Date) {
    // Datadog expects seconds.
    timestamp = Math.round(date.getTime() / 1000);
  } else if (date instanceof Number) {
    // Make sure it is an integer, not a float.
    timestamp = Math.round(date);
  }
  return timestamp;
}
521074
function(date, format) {
            var i, replacements,
                locale = locale_name();
            if(format && locale_uses_day_before_month()) {
                replacements = this.DAY_FIRST_FORMATS;
                for(i = 0; i < replacements.length; i++) {
                    format = format.replace(replacements[i][0], replacements[i][1]);
                }
            }
            if(format && locale in this.CUSTOM_LOCALE_FORMATS) {
                replacements = this.CUSTOM_LOCALE_FORMATS[locale];

                for(i = 0; i < replacements.length; i++) {
                    format = format.replace(replacements[i][0], replacements[i][1]);
                }
            }
            return format_date(date, format);
        }
1067795
function defaultFormat(d) {
  if ((0, _DateUtils.isDate)(d)) {
    var year = d.getFullYear();
    var month = '' + (d.getMonth() + 1);
    var day = '' + d.getDate();
    return year + '-' + month + '-' + day;
  }
  return '';
}
111990
def date_clean(date, dashboard_style=False):
  
  if dashboard_style:
    dt = str(date)
    out = dt[4:6] + '/' + dt[6:] + '/' + dt[:4]
  else:
    dt = str(date)
    out = dt[:4] + '-' + dt[4:6] + '-' + dt[6:]
  return out
352516
def _parsed_string_to_bounds(date_type, resolution, parsed):
    
    if resolution == 'year':
        return (date_type(parsed.year, 1, 1),
                date_type(parsed.year + 1, 1, 1) - timedelta(microseconds=1))
    elif resolution == 'month':
        if parsed.month == 12:
            end = date_type(parsed.year + 1, 1, 1) - timedelta(microseconds=1)
        else:
            end = (date_type(parsed.year, parsed.month + 1, 1) -
                   timedelta(microseconds=1))
        return date_type(parsed.year, parsed.month, 1), end
    elif resolution == 'day':
        start = date_type(parsed.year, parsed.month, parsed.day)
        return start, start + timedelta(days=1, microseconds=-1)
    elif resolution == 'hour':
        start = date_type(parsed.year, parsed.month, parsed.day, parsed.hour)
        return start, start + timedelta(hours=1, microseconds=-1)
    elif resolution == 'minute':
        start = date_type(parsed.year, parsed.month, parsed.day, parsed.hour,
                          parsed.minute)
        return start, start + timedelta(minutes=1, microseconds=-1)
    elif resolution == 'second':
        start = date_type(parsed.year, parsed.month, parsed.day, parsed.hour,
                          parsed.minute, parsed.second)
        return start, start + timedelta(seconds=1, microseconds=-1)
    else:
        raise KeyError
1107704
def set_date_bounds(self, date):
        '''
        
        '''
        if date is not None:
            split = date.split('~')
            if len(split) == 1:
                self._lbound = ts2dt(date)
                self._rbound = ts2dt(date)
            elif len(split) == 2:
                if split[0] != '':
                    self._lbound = ts2dt(split[0])
                if split[1] != '':
                    self._rbound = ts2dt(split[1])
            else:
                raise Exception('Date %s is not in the correct format' % date)