php strtotime some day un complete - php

I have some date, like:
20 November 06:10
12 November 08:12
10 October 13:23
There all in the past 6 months, Now I want to strtotime() them, but they are all un complete (lack of year), how to make some process so that I could strtotime() them?

Try this:
$dates = array("10 October 13:23", "12 November 08:12", "10 October 13:23");
foreach($dates as $d){
$exploded = explode(" ", $d);
$newDate = array_slice($exploded, 0,2,true)+array(2=>"2012")+array(3 => $exploded[2]);
//print_r($newDate);
$time = strtotime(implode($newDate));
echo $time."<br/>";
}
The output i got is:
1349868180
1352704320
1349868180
The logic is:
You lack the year, so I exploded the dates into an array to slice them, insert the year (the +array(2=>"2012") part) and glue them again with implode, and then run the strtotime.
This work only for this year, so you can use this logic to add the year to all your dates, or in the future there will be absolutely no way to filter dates from different years.
I added the dates into an array for loop through all of them, you can use the loop other ways, depending on where you have all your dates stored. For example if they are in a database you can include the script in the while($row = mysqli_fetch_assoc($result)) part where $d would be $row['date'] instead.

You should use the DateTime class and its createFromFormat and getTimeStamp methods instead of strtotime.

print_r(date_parse_from_format("d F H:i", '20 November 06:10'));
gives you:
Array
(
[year] =>
[month] => 11
[day] => 20
[hour] => 6
[minute] => 10
[second] => 0
[fraction] =>
[warning_count] => 0
[warnings] => Array
(
)
[error_count] => 0
[errors] => Array
(
)
[is_localtime] =>
)

Related

Date_sub() on a date array

I am trying to remove exactly 1 year from every date of an array.
Here is the original $periods array
Array ( [0] => 2020-06-01 [1] => 2020-07-01 [2] => 2020-08-01 [3] => 2020-09-01 [4] => 2021-01-01 [5] => 2022-01-01 [6] => 2022-06-01 [7] => 2022-08-01 [8] => 2022-10-01 [9] => 2023-04-01 )
I tried
foreach ($periods as $p) {
date_sub($p,date_interval_create_from_date_string("1 year"));
echo date_format($p,"Y-m-d"). '<br>';
}
It doesn't return anything...
Any pointers would be appreciated.
First set your array values datatype to string => "2020-06-01" , and try this code:
foreach ($periods as $period) {
// convert date string to date model object
$periodDate = date_create($period);
// subtract date string from coverted date string
date_sub($periodDate,date_interval_create_from_date_string("1 year"));
// covert subtracted date object to readable date fromat
echo date_format($periodDate,"Y-m-d");
}
You can transform dates using next code:
$res = array_map(
// convert source string to time, subtract 1 year interval
// and convert to 'Y-m-d' format in singe function
fn($p) => date('Y-m-d', strtotime("-1 year", strtotime($p))),
$periods
);
run PHP online

Breaking up a string(2011-09-10) with PHP

I'm passing a date value in the following format.
2011-09-10
I need to break it into 3 variables using php.
$day =
$month =
$year =
How should I go about doing this?
For your case, $parts = explode("-", $inputstr); would work (and then year is $parts[0] et cetera).
But, for more general date parsing, you might want strptime() (if you know the format) or strtotime() (if you don't).
In one line:
list($year, $month, $day) = explode('-', '2011-09-10');
$date = getdate(strtotime("2011-09-10"));
print_r($date);
Output:
Array
(
[seconds] => 0
[minutes] => 0
[hours] => 0
[mday] => 10
[wday] => 6
[mon] => 9
[year] => 2011
[yday] => 252
[weekday] => Saturday
[month] => September
[0] => 1315612800
)
See PHP's explode() function

Identify date-related text in a longer message

I'm currently writing a script that would extract all the dates from a message and convert them to timestamps. PHP's strtotime (similar to Unix's date -c 'some date') would be perfect for this, as it recognizes all kinds of dates, such as:
5pm today
2010-11-15 16:30
Thursday 8:00
However, I'm having trouble finding those dates in the first place. For example, in the following string,
I'll be there for dinner tomorrow at 9:00pm
I need to isolate "tomorrow at 9:00pm", as that's the part that strtotime recognizes.
Is there a regular expression or something similar that would return me all dates that can be parsed by strtotime?
The only thing I can think of is date_parse. A regular expression that matches any format accepted by strtotime would be huge.
An example of date_parse:
$str = "I'll be there for dinner tomorrow at 9:00pm";
$parsed = date_parse($str);
print_r($parsed);
It would output something like this (I removed the unimportant parts from it to make it the result lighter):
Array
(
[year] =>
[month] =>
[day] =>
[hour] => 21 // 9:00pm
[minute] => 0 // 9:00pm
[second] => 0 // 9:00pm
[fraction] => 0
[warning_count] => 1
[is_localtime] => 1
[zone_type] => 2
[zone] => -540
[is_dst] =>
[tz_abbr] => I
[relative] => Array
(
[year] => 0
[month] => 0
[day] => 1 // tomorrow (would be -1 for yesterday, etc.)
[hour] => 0
[minute] => 0
[second] => 0
)
)
Whether this works for you depends primarily on what your input looks like. If you have more than one instance of a date in your input string, it will not work as expected.
This might not be totally efficient, but should work for any date string that consists of up to 5 words in length. I would write the function, but I think you'll get the idea with the comments below...
$words = explode(' ',$original_string);
// Use the array_chunk() function break up this array into 1-word,
// 2-word, 3-word, and 4-word long substrings of the original string
// Reform them back into strings and pass each one through strtodate()

Extract the Day / Month / Year from a Timestamp on MYSQL

I have :
$date = $actualite['date'];
$actualite['date'] is a TIMESTAMP
And I was wondering how can I extract from this timestamp the day, then the month, then the year in 3 variables.
Thank you for your help :)
Use date_parse($actualite['date']);, which will return an array containing the day, month, year and other items.
http://www.php.net/manual/en/function.date-parse.php
Example:
<?php
print_r(date_parse("2006-12-12 10:00:00.5"));
?>
Output:
Array
(
[year] => 2006
[month] => 12
[day] => 12
[hour] => 10
[minute] => 0
[second] => 0
[fraction] => 0.5
[warning_count] => 0
[warnings] => Array()
[error_count] => 0
[errors] => Array()
[is_localtime] =>
)
You can extract the values directly within your MySQL query
SELECT DAY( <TIMESTAMP_FIELD> ) AS DAY,
MONTH( <TIMESTAMP_FIELD> ) AS MONTH,
YEAR( <TIMESTAMP_FIELD> ) AS YEAR
FROM <TABLE>
Another way with more options for formatting would be:
$date = date_create($myTimeStamp); // From database "2020-04-09 17:59:20"
$formatedDate = date_format($date, "d/m/y"); // --> 09/04/20
https://www.php.net/manual/en/datetime.format.php
It might be less intuitive than date_parse() but gives you more options as far as I can see.

break apart formatted date into individual month/day/year hour/minute/second in php

I have a date in the following format
November 18, 2009, 3:00PM
How can i break that up so that i can store each value as its own variable?
such as...
$month //November
$day //18
$year //2009
$hour //03
$minute //00
$ampm //PM
Use the 'date_parse' (http://nl2.php.net/manual/en/function.date-parse.php) function. It returns an array with the parsed items:
Array
(
[year] => 2006
[month] => 12
[day] => 12
[hour] => 10
[minute] => 0
[second] => 0
[fraction] => 0.5
[warning_count] => 0
[warnings] => Array()
[error_count] => 0
[errors] => Array()
[is_localtime] =>
)
Convert your date into a timestamp, then with the timestamp you can easily get your parts. An other way is using a regular expression.
$str = "November 18, 2009, 3:00PM";
list($month,$day,$year,$time) = preg_split('/[ ,]/',$str,false,PREG_SPLIT_NO_EMPTY);
preg_match('/([0-9]+):([0-9]+)([AP]M)/',$time,$timeparts);
list($time,$hour,$minute,$ampm) = $timeparts;
echo "\$month $month\n";
echo "\$day $day\n";
echo "\$year $year\n";
echo "\$hour $hour\n";
echo "\$minute $minute\n";
echo "\$ampm $ampm\n";
Output
$month November
$day 18
$year 2009
$hour 3
$minute 00
$ampm PM
More complex solution.
If your dates may be in the different standards you can use date() function (http://php.net/manual/en/function.date.php) + strtotime() function (http://php.net/manual/en/function.strtotime.php), which parse string and returns the unix timestamp.
For example, if you want to get a year from your date string you could write next code:
$date = 'November 18, 2009, 3:00PM';
$year = date('Y', strtotime($date));
Or, if you want to know how much days in the month in date you get, you could write such code:
$date = 'November 18, 2009, 3:00PM';
$num_of_days = date('t', strtotime($date));
't' returns the number of days in the given month.

Categories