Parsing dates in php

Parsing a string for dates in php

Solution 1: You can create a simple regex for this operation can you check out the code below; You will get an output like that; And working example is here http://ideone.com/LuQqEN Solution 2: i use same as cihan-uygun code but my Regx expression is little change here is code example : I need dates output from these strings Solution 1: Try to set the locale to Russian as hinted in the manual: Solution 2: you could try take a locale parameter and call locale_set_default($locale) before doing the date parsing. Solution 1: If you want to handle it in PHP, your best bet is to use the function which converts a string into a time that can then be manipulated with the function.

Parse multiple dates from same string in php

You can create a simple regex for this operation can you check out the code below;

)/i"; //This will match a letters + space + 4 digit number together $inputString = "juny 2014 october 2014 february 2016 march 2017 july 2010 FEBRUARY 2014"; $matchCount = preg_match_all($regexPattern, $inputString, $matches); print_r($matches); ?> 

You will get an output like that;

[0] => Array ( [0] => juny 2014 [1] => october 2014 [2] => february 2016 [3] => march 2017 [4] => july 2010 [5] => FEBRUARY 2014 ) [1] => Array ( [0] => juny 2014 [1] => october 2014 [2] => february 2016 [3] => march 2017 [4] => july 2010 [5] => FEBRUARY 2014 ) 

And working example is here http://ideone.com/LuQqEN

i use same as cihan-uygun code but my Regx expression is little change

example : I need dates output from these strings

2020 Ice Harbor All-Ages Master/Expert — Nov 21, 2020
2020 Ice Harbor Scholastic Open (Nov 21, 2020 — Nov 22, 2020)

 1\, 1/i"; preg_match_all($regexPattern, $stringgosehere, $matches); ?> 

Parsing HTTP ‘Last-Modified’ Date string in PHP, I am using FileAPI to get the HTTP-header Last-Modified time of a file, which is returning the following string: Fri Oct 25 2013 12:04:10 GMT+0100 (GMT Daylight Time) This is then posted to PHP and I need it converted to something sensible, preferably a timestamp. Before you suggest it, strtotime () …

Parsing a string for dates in PHP

Parsing a string fo r dates in PHP — PHP [ Glasses to protect eyes while coding : https://amzn.to/3N1ISWI ] Parsing a string fo r dates in PHP — PHP Disclaime

Parsing localized date strings in PHP

Try to set the locale to Russian as hinted in the manual:

Month and weekday names and other language dependent strings respect the current locale set with setlocale() (LC_TIME ).

you could try take a locale parameter and call locale_set_default($locale) before doing the date parsing.

$originalLocale = locale_get_default(); $locale ? $locale : $originalLocale; locale_set_default(locale); // date parsing code locale_set_default($originalLocale); 

I haven’t testing this but it’s work a try. FYI, I believe the locale string for Russian is «ru-Latn»

Читайте также:  Php text output header

I see that the question is already answered but none of the solutions provided worked for me.

if(!preg_match('/^en_US/', $locale)) < $months_short = array('jan' =>t('jan'), 'feb' => t('feb'), 'mar' => t('mar'), 'apr' => t('apr'), 'may' => t('may'), 'jun' => t('giu'), 'jul' => t('lug'), 'aug' => t('ago'), 'sep' => t('set'), 'oct' => t('ott'), 'nov' => t('nov'), 'dec' => t('dec')); foreach ($months_short as $month_short => $month_short_translated) < $date = preg_replace('/'.$month_short_translated.'/', $month_short, strtolower($date)); >> $pieces = date_parse_from_format($format,$date); if($pieces && $pieces['error_count'] == 0 && checkdate($pieces['month'], $pieces['day'], $pieces['year']))

Where t() returns the translated abbreviation for the month.

Probably not the best solution ever (because it fails if there is no valid translation) but it works for my case.

PHP Parse Date From String, 4 Answers. You can do that using the DateTime object. $Date = new DateTime (‘2013-07-09T04:58:23.075Z’); //create dateTime object $Date->setTimezone (new DateTimeZone (‘Europe/Amsterdam’)); //set the timezone echo $Date->format (‘d/m/Y H:i’);

Parse a date string

If you want to handle it in PHP, your best bet is to use the strtotime() function which converts a string into a time that can then be manipulated with the date() function.

So you’d do something like:

$dateStr = date('Y-m-d', strtotime('03/21/2011')); 

The nice thing about using strtotime() is that you don’t have to worry about the exact format of the string you pass in. As long as it’s something semi-reasonable, it’ll will convert it.

So it would handle 03/21/2011 , 3-21-2011 , 03-21-11 without any modifications or special cases.

You can parse it even from mysql

select str_to_date('03/21/2011','%m/%d/%Y') 
$date = '03/21/2011'; $timestamp = strtotime($date); $sqlDate = date('Y-m-d', $timestamp); 

That should do what you need.

PHP date_parse_from_format() Function, PHP date_parse_from_format() Function, The date_parse_from_format() function accepts a format string and a date string as parameters and, returns information about the given date in the specified for

PHP — Parsing String As Past Date

Your approach is fine, as there is no date format to get what you want. Another approach could be using the DateTime class:

$datetime = new DateTime($raw_time); if ($datetime > new DateTime()) < $datetime->modify('-1 year'); > 

You could test which one of the two approaches is faster. My guess is that this is a micro-optimization that won’t make a lot of difference.

PHP | Converting string to Date and DateTime, Last Updated : 31 Jul, 2021. Converting the string to Date and DateTime uses several functions/methods like strtotime (), getDate (). We will see what these functions do. strtotime () – This is basically a function which returns the number of seconds passed since Jan 1, 1970, just like a linux machine timestamp.

Читайте также:  Удалите неиспользуемый код javascript вордпресс

Источник

Date Parsing in PHP

Date parsing is an essential function in PHP that allows users to convert a string representation of a date into a timestamp or a DateTime object. This function is useful in scenarios where dates are stored as strings, and it is necessary to perform date arithmetic or comparison operations. In this article, we will explore the various aspects of date parsing in PHP and provide a step-by-step guide to using the date_parse_from_format() function.

Understanding Date Parsing

Before we dive into the specifics of date parsing in PHP, it is important to understand what date parsing is and how it works. Date parsing refers to the process of extracting a date or time from a string representation of a date. For example, the string «2023-03-03» can be parsed into a timestamp or a DateTime object, which can then be used for various operations.

Date parsing can be challenging due to the various formats that dates can be represented in, such as «YYYY-MM-DD,» «MM/DD/YYYY,» «DD-MMM-YYYY,» and so on. To parse a date correctly, it is necessary to specify the format of the input string using a format string.

The date_parse_from_format() Function

In PHP, the date_parse_from_format() function is used to parse a date string using a specific format. This function returns an associative array containing detailed information about the parsed date, including the year, month, day, hour, minute, second, timezone, and more.

The syntax of the date_parse_from_format() function is as follows:

date_parse_from_format($format, $date_string);

Where $format is a string specifying the format of the input date string, and $date_string is the input date string that needs to be parsed.

Let’s take a look at an example:

 $date_string = "2023-03-03 10:30:00"; $format = "Y-m-d H:i:s"; $date_array = date_parse_from_format($format, $date_string); print_r($date_array);

The output of this code will be:

Array ( [year] => 2023 [month] => 3 [day] => 3 [hour] => 10 [minute] => 30 [second] => 0 [fraction] => [warning_count] => 0 [warnings] => Array() [error_count] => 0 [errors] => Array() [is_localtime] => [zone_type] => 1 [zone] => -14400 [is_dst] => )

As you can see, the date_parse_from_format() function has successfully parsed the input date string «2023-03-03 10:30:00» using the format string «Y-m-d H:i:s.»

Using the date_parse_from_format() function, you can parse dates represented in various formats, including the day of the week, the month name, the AM/PM indicator, and more. You can also specify optional or alternative date and time formats using square brackets and the pipe symbol, respectively.

Conclusion

In conclusion, date parsing is an essential function in PHP that allows you to convert a string representation of a date into a timestamp or a DateTime object.

Источник

date_parse_from_format

Returns associative array with detailed info about given date/time.

Parameters

Documentation on how the format is used, please refer to the documentation of DateTimeImmutable::createFromFormat() . The same rules apply.

String representing the date/time.

Return Values

Returns associative array with detailed info about given date/time.

The returned array has keys for year , month , day , hour , minute , second , fraction , and is_localtime .

If is_localtime is present then zone_type indicates the type of timezone. For type 1 (UTC offset) the zone , is_dst fields are added; for type 2 (abbreviation) the fields tz_abbr , is_dst are added; and for type 3 (timezone identifier) the tz_abbr , tz_id are added.

The array includes warning_count and warnings fields. The first one indicate how many warnings there were. The keys of elements warnings array indicate the position in the given datetime where the warning occurred, with the string value describing the warning itself. An example below shows such a warning.

The array also contains error_count and errors fields. The first one indicate how many errors were found. The keys of elements errors array indicate the position in the given datetime where the error occurred, with the string value describing the error itself. An example below shows such an error.

The number of array elements in the warnings and errors arrays might be less than warning_count or error_count if they occurred at the same position.

Changelog

Version Description
7.2.0 The zone element of the returned array represents seconds instead of minutes now, and its sign is inverted. For instance -120 is now 7200 .

Examples

Example #1 date_parse_from_format() example

The above example will output:

Array ( [year] => 2009 [month] => 1 [day] => 6 [hour] => 13 [minute] => 0 [second] => 0 [fraction] => [warning_count] => 0 [warnings] => Array ( ) [error_count] => 0 [errors] => Array ( ) [is_localtime] => 1 [zone_type] => 1 [zone] => 3600 [is_dst] => )

Example #2 date_parse_from_format() with warnings example

$date = «26 August 2022 22:30 pm» ;
$parsed = date_parse_from_format ( «j F Y G:i a» , $date );

echo «Warnings count: » , $parsed [ ‘warning_count’ ], «\n» ;
foreach ( $parsed [ ‘warnings’ ] as $position => $message ) echo «\tOn position < $position >: < $message >\n» ;
>
?>

The above example will output:

Warnings count: 1 On position 23: The parsed time was invalid

Example #3 date_parse_from_format() with errors example

$date = «26 August 2022 CEST» ;
$parsed = date_parse_from_format ( «j F Y H:i» , $date );

echo «Errors count: » , $parsed [ ‘error_count’ ], «\n» ;
foreach ( $parsed [ ‘errors’ ] as $position => $message ) echo «\tOn position < $position >: < $message >\n» ;
>
?>

The above example will output:

Errors count: 3 On position 15: A two digit hour could not be found On position 19: Data missing

See Also

User Contributed Notes

  • Date/Time Functions
    • checkdate
    • date_​add
    • date_​create_​from_​format
    • date_​create_​immutable_​from_​format
    • date_​create_​immutable
    • date_​create
    • date_​date_​set
    • date_​default_​timezone_​get
    • date_​default_​timezone_​set
    • date_​diff
    • date_​format
    • date_​get_​last_​errors
    • date_​interval_​create_​from_​date_​string
    • date_​interval_​format
    • date_​isodate_​set
    • date_​modify
    • date_​offset_​get
    • date_​parse_​from_​format
    • date_​parse
    • date_​sub
    • date_​sun_​info
    • date_​sunrise
    • date_​sunset
    • date_​time_​set
    • date_​timestamp_​get
    • date_​timestamp_​set
    • date_​timezone_​get
    • date_​timezone_​set
    • date
    • getdate
    • gettimeofday
    • gmdate
    • gmmktime
    • gmstrftime
    • idate
    • localtime
    • microtime
    • mktime
    • strftime
    • strptime
    • strtotime
    • time
    • timezone_​abbreviations_​list
    • timezone_​identifiers_​list
    • timezone_​location_​get
    • timezone_​name_​from_​abbr
    • timezone_​name_​get
    • timezone_​offset_​get
    • timezone_​open
    • timezone_​transitions_​get
    • timezone_​version_​get

    Источник

Оцените статью