Convert a DateTime compatible date or expression into an ES compatible date format

@param string $text Date as text.

@return string
519264
private function createDateFromText($text)
    {
        try {
            $date = new \DateTime($text);
        } catch (\Exception $e) {
            $date = new \DateTime(self::DEFAULT_TO_DATE);
        }

        return $date->format('Y-m-d');
    }
670409
protected function _convertDate($date)
    {
        // regexps to validate input
        $datePatterns = [
            "/^([0-9]{2})\.([0-9]{4})/" => "EUR2", // MM.YYYY
            "/^([0-9]{2})\.([0-9]{2})/" => "EUR1", // DD.MM
            "/^([0-9]{2})\/([0-9]{4})/" => "USA2", // MM.YYYY
            "/^([0-9]{2})\/([0-9]{2})/" => "USA1" // DD.MM
        ];

        // date/time formatting rules
        $dateFormats = [
            "EUR1" => [2, 1],
            "EUR2" => [2, 1],
            "USA1" => [1, 2],
            "USA2" => [2, 1]
        ];

        // looking for date field
        $dateMatches = [];
        $stringModifier = getStr();
        foreach ($datePatterns as $pattern => $type) {
            if ($stringModifier->preg_match($pattern, $date, $dateMatches)) {
                $date = $dateMatches[$dateFormats[$type][0]] . "-" . $dateMatches[$dateFormats[$type][1]];
                break;
            }
        }

        return $date;
    }
1041395
public function _(string $text) : string
    {
        return $this->c->translator instanceof ITranslator ? $this->c->translator->translate($text) : $text;
    }
840773
public static function translate($text)
    {
        $args = func_get_args();
        unset($args[0]);
        
        if (isset(self::$messages[$text])) {
            $text = self::$messages[$text];
        }
        
        return vsprintf($text, $args);
    }
1362530
public function processText(string $text): string
    {
        $text = str_replace("<br>", "", $text);
        $text = str_replace("<br/>", "", $text);
        $text = str_replace("<br />", "", $text);
        $text = str_replace("\n", "<br>", $text);
        $text = str_replace("\t", "&nbsp; &nbsp; &nbsp;", $text);

        return preg_replace($this->pattern, $this->replace, $text);
    }
1297383
public function escape(string $text): string
    {
        $replacements = [
            '&' => '&amp;',
            '<' => '&lt;',
            '>' => '&gt;',
        ];

        return str_replace(array_keys($replacements), array_values($replacements), $text);
    }
1068553
private function replacePlaceholdersInText($text): string
    {
        $text = str_replace(array_keys($this->placeholders), $this->placeholders, $text);
        
        return $text;
    }
105078
public function normalizeText( $text )
    {
        if ( $this->searchHandler instanceof LegacyHandler )
        {
            $searchEngine = new eZSearchEngine();
            return $searchEngine->normalizeText( $text );
        }

        return $text;
    }
265025
private function decodeContentTypesFromText($text)
    {
        $contenttypes = [];

        if ((substr($text, 0, 1) == '(') &&
            (substr($text, -1) == ')')
        ) {
            $contenttypes = explode(',', substr($text, 1, -1));
        } else {
            $contenttypes[] = $text;
        }

        $instance = $this;
        $contenttypes = array_map(
            function ($name) use ($instance) {
                $ct = $instance->getContentType($name);

                return $ct['slug'];
            },
            $contenttypes
        );

        return $contenttypes;
    }
124217
public function render($text)
    {
        $text = trim(str_replace(array("\r\n", "\r"), "\n", $text), "\n");

        foreach ($this->rules as $regex => $replacement) {
            if (is_callable($replacement)) {
                $text = preg_replace_callback($regex, $replacement, $text);
            } else {
                $text = preg_replace($regex, $replacement, $text);
            }
        }

        return trim($text);
    }
1016556
public function convertToDateTime(string $string) : \DateTime
    {
        $string = trim($string);
        foreach ([$this->getLastGuessedFormat(), $this->guessDateFormat($string) ] as $format) {
            $date = $this->newDate((string) $format, $string);
            if ($date instanceof \DateTime) {
                $date->setTimezone($this->getTimezone());

                return $date;
            }
        }

        return $this->stringToDateTime($string);
    }
121317
def extractDate(text):
    
    if type(text) is datetime.date:
        return text
    match = date_format.search(text.lower())
    if not match:
        raise ValueError('unsupported date format: {0}'.format(text.lower()))
    # convert DD.MM.YYYY into YYYY-MM-DD
    if match.group('month'):
        if not match.group('month') in month_names:
            raise ValueError('unknown month names: "{0}"'
                             .format(match.group('month')))
        year = int(match.group('year'))
        return datetime.date(
            year if year > 2000 else 2000 + year,
            int(month_names[match.group('month')]),
            int(match.group('day')))
    else:
        parts = list(map(lambda v: int(v), '-'.join(reversed(
            match.group('datestr').split('.'))).split('-')))
        if parts[0] < 2000:
            parts[0] += 2000
        return datetime.date(*parts)
998213
public function format(string $text) : string
    {
        if ($text === '') {
            return $text;
        }

        $startCodes = [];
        $endCodes = [];

        if ($this->foregroundColor !== null) {
            $startCodes[] = self::$supportedForegroundColors[$this->foregroundColor][0];
            $endCodes[] = self::$supportedForegroundColors[$this->foregroundColor][1];
        }

        if ($this->backgroundColor !== null) {
            $startCodes[] = self::$supportedBackgroundColors[$this->backgroundColor][0];
            $endCodes[] = self::$supportedBackgroundColors[$this->backgroundColor][1];
        }

        foreach ($this->textStyles as $style) {
            $startCodes[] = self::$supportedTextStyles[$style][0];
            $endCodes[] = self::$supportedTextStyles[$style][1];
        }

        if (count($startCodes) === 0 && count($endCodes) === 0) {
            // No point in trying to format the text
            return $text;
        }

        return sprintf(
            "\033[%sm%s\033[%sm",
            implode(';', $startCodes),
            $text,
            implode(';', $endCodes)
        );
    }
212320
function convertHeaderText( $text )
    {
        $charset = $this->contentCharset();
        if ( $charset != 'us-ascii' )
        {
            $newText = $this->encodeMimeHeader( $text );
            return $newText;
        }
        return $text;
    }
887234
public static function Parse($text)
	{
		$text = strtoupper( trim( $text ) );

		$result = preg_match( "/^--(?<month>\d{1,2})(?<offset>(?=[+\-a-zA-Z])(([+\-]\d{2}(:\d{2}))|Z|((\?!-|\\+)(?i)[^0-9].{3,})))?$/i", $text, $matches );
		if ( ! $result )
		{
			throw XPath2Exception::withErrorCodeAndParams( "FORG0001", Resources::FORG0001, array( $text, "xs:gYear" ) );
		}

		$error =  empty( $matches['month'] ) || $matches['month'] > 12 || $matches['month'] < 1;
		$offsetMatches = null;
		if ( ! $error && ! empty( $matches['offset'] ) )
		{
			$error = $matches['offset'] != "Z" &&
			! in_array( $matches['offset'], timezone_identifiers_list() ) &&
			! preg_match( "/^[+-](?<hours>\d{2})(:(?<minutes>\d{2}))?$/", $matches['offset'], $offsetMatches );

			if ( ! $error && ! is_null( $offsetMatches ) )
			{
				$error = empty( $offsetMatches['hours'] ) || $offsetMatches['hours'] > 14 ||
				empty( $offsetMatches['minutes'] ) || $offsetMatches['minutes'] > 59;
			}

		}

		if ( $error )
		{
			throw XPath2Exception::withErrorCodeAndParams( "FORG0001", Resources::FORG0001, array( $text, "xs:gMonth" ) );
		}

		$dateTime = \DateTime::createFromFormat( "!--mO", $text );
		if ( $dateTime )
			return new GMonthValue( $dateTime );

		$dateTime = \DateTime::createFromFormat( "!--m\Z", $text );
		if ( $dateTime )
			return new GMonthValue( $dateTime );

		$dateTime = \DateTime::createFromFormat( "!--m", $text );
		if ( $dateTime )
			return new GMonthValue( $dateTime );

		throw XPath2Exception::withErrorCodeAndParams( "FORG0001", Resources::InvalidFormat, array( $text, "xs:gMonth" ) );
	}
720083
public function format($text)
    {
        $lines = explode("\n", $text);
        foreach ($lines as &$line) {
            $line = ($this->quote) . str_repeat(' ', $this->indent) . $line;
        }
        return Colour::colour(implode("\n", $lines), $this->foregroundColors, $this->backgroundColors);
    }
499403
public function parseDate($string)
    {
        try {
            return new \DateTime($string);
        } catch (ParsingException $ex) {
            $exception = new ParsingException('The date is '
                      . 'not parsable', 0, $ex);
            throw $exception;
        }
        
    }