PHP Parse Date String - php

If I've got a date string:
$date = "08/20/2009";
And I want to separate each part of the date:
$m = "08";
$d = "20";
$y = "2009";
How would I do so?
Is there a special date function I should be using? Or something else?
Thanks!

One way would be to do this:
$time = strtotime($date);
$m = date('m', $time);
$d = date('d', $time);
$y = date('Y', $time);

explode will do the trick for that:
$pieces = explode("/", $date);
$d = $pieces[1];
$m = $pieces[0];
$y = $pieces[2];
Alternatively, you could do it in one line (see comments - thanks Lucky):
list($m, $d, $y) = explode("/", $date);

Check out PHP's date_parse function. Unless you're sure input will always be in a consistent format, AND you validate it first, it is much more stable and flexible, (not to mention easier), to let PHP try to parse the format for you.
e.g.
<?php
//Both inputs should return the same Month-Day-Year
print_r(date_parse("2012-1-12 51:00:00.5"));
print_r(date_parse("1/12/2012"));
?>

If you have a given format you should use a date object.
$date = DateTime::createFromFormat('m/d/Y', '08/20/2009');
$m = $date->format('m');
$d = $date->format('d');
$y = $date->format('Y');
Note you can certainly use only one call to DateTime::format().
$newFormat = $date->format('d-m-Y');

Is it always like that? Or will it be in any sort of file format?
Try strtotime.
Something like:
if(($iTime = strtotime($strDate))!==false)
{
echo date('m', $iTime);
echo date('d', $iTime);
echo date('y', $iTime);
}

how about this:
list($m, $d, $y) = explode("/", $date);
A quick one liner.

For internationalized date parsing, see IntlDateFormatter::parse - http://php.net/manual/en/intldateformatter.parse.php
For example:
$f = new \IntlDateFormatter('en_gb', \IntlDateFormatter::SHORT, \IntlDateFormatter::NONE);
$dt = new \DateTime();
$dt->setTimestamp($f->parse('1/2/2015'));

Dominic's answer is good, but IF the date is ALWAYS in the same format you could use this:
$m = substr($date,0,2);
$d = substr($date,3,2);
$y = substr($date,-4);
and not have to use an array or explode
Bill H

Related

How to make PHP see a datetime value for what it is

I'm passing the following value via URL to PHP:
&newtimestamp=2016-12-21%2014:44:44.
Instead of %20 I've tried with +.
In PHP I have this:
$newtimestamp = $_GET["newtimestamp"];
Which correctly shows the timestamp if I do:
echo ($newtimestamp);
But when trying:
echo date_format($newtimestamp,'U');
or
echo date_format($newtimestamp,'Y-m-d H:i:s');
I get no output at all. And later in the script, the input is used to compare against an SQL table:
$sql = ("SELECT sender,subject,timestamp,threadid,username,notify,msgtype FROM Messages WHERE sender = '$usernametmp' AND subject !='' AND timestamp > '$newtimestamp' ORDER BY timestamp");
And I get no results at all.
I do get results If I manually set the timestamp to
$newtimestamp = '1985-10-07 11:42:12';
I was thinking that I need to define it as datetime with:
$timestamp = new DateTime($newtimestamp);
But then I get a server error.
PHP version is 5.3, by the way. and needs to be changed by my hosting provider. If that's the solution, is there a lot of stuff running with 5.3 that will no longer work with 5.5 or 5.6 (this is what they offer)?
I hope someone can see what I'm doing wrong here, thanks in advance!
You need to use the date_create function and decode the URL on the GET like this:
<?php
$newtimestamp=date_create(urldecode($_GET['newtimestamp']));
echo date_format($newtimestamp,"Y/m/d H:i:s");
You cannot compare human time to unix time format, unix time looks like this
1483319956
So you probably need a function to help you do that
try this custom function i wrote
change_date_to_timestamp($date_string)
{
$array = explode(' ', $date_string);
$date = $array[0];
$date = explode('-', $date);
$year = (int)$date[0];
$month = (int)$date[1];
$day = (int)$date[2];
$hour = 00;
$minute = 00;
$second = 00;
if (isset($array[1])) {
$time = $array[1];
$time = explode(':', $time);
$hour = (int)$time[0];
$minute = (int)$time[1];
$second = (int)$time[2];
}
$stamp = mktime($hour, $minute, $second, $month, $day, $year);
return $stamp;
}
Refactor as pleased

Verifiying 2 date to make sure they're valid dates

I am working with a date which is formatted like so:
25/02/1994 - 15/03/2000
To get each date I am using the explode function to separate each date between dash
$newdate = explode("-",$olddate);
Now my problem is, if it was just one date I could split it up in to 3 parts, the day, month, year and use the checkdate function to validate the month, but because I am using explode I cannot split it up like that (to my knowledge)
What would be the best way to validate the date for legitimacy?
You have a good start, after you exploded your string by -, just simply loop through each date with array_reduce() and reduce it to 1 value.
In the anonymous function you just explode() each date and check with checkdate() if it is a valid date, e.g.
<?php
$str = "25/02/1994 - 15/03/2000";
$dates = explode("-", $str);
if(array_reduce($dates, function($keep, $date){
list($day, $month, $year) = array_map("trim",explode("/", $date));
if(!checkdate($month, $day, $year))
return $keep = FALSE;
return $keep;
}, TRUE)) {
echo "all valid dates";
}
?>
$date = '25/02/1994 - 15/03/2000';
$date_array = explode("-", $date);
$first_date = explode("/", trim($date_array[0]));
$second_date = explode("/", trim($date_array[1]));
if(checkdate($first_date[1],$first_date[0],$first_date[2])){
//do stuff
}
if(checkdate($second_date[1],$second_date[0],$second_date[2])){
//do stuff
}
or, what Daan suggested using the DateTime object.
$date = '25/02/1994 - 15/03/2000';
$date_array = explode("-", $date);
$date1 = DateTime::createFromFormat('j-M-Y', $date_array[0]);
$date2 = DateTime::createFromFormat('j-M-Y', $date_array[1]);
if($date1){
//do stuff
}
if($date2){
//do stuff
}

Read values from URL parameter where slashes are represented by %2F in PHP

The datepicker I'm using passes the date to a php script on form submit.
The URL parameter is as follows - datepicker1=12%2F09%2F2014
I can store 12%2F09%2F2014 in a variable.
$datepicker1 = $_GET['datepicker1'];
I also have 3 other variables namely:
$day
$month
$year
How do add individual day, month, and year to their respective variables by extracting them from variable $datepicker1?
Try this:
$datepicker1 = "12%2F09%2F2014";
$val = urldecode($datepicker1);
$array = explode('/', $val);
print_r($array);
The $array variable is your result.
Now you can assign array value into your $day, $month, $year variable like this:
$day = $array[0];
$month = $array[1];
$year = $array[2];
Now you can store it into database.
I hope this will helpful for you.
Thanks
use this urldecode() function
$date = urldecode("12%2F09%2F2014");
$year = date('Y', strtotime($date));
$mon = date('m', strtotime($date));
$day = date('d', strtotime($date));
You Can use sbstr() to get the value.
Suppose for date $date=substr($datepicker1,0,2);
Similarly others.. :)
$date= urldecode("12%2F09%2F2014");
echo substr($date, 0, 2);
echo "<br>";
echo substr($date, 3, 2);
echo "<br>";
echo substr($date, 6, 4);
echo "<br>";
I tried the above and it seems to work fine for me.
Instead of echo-ing - will add these to variables.
The array solution provided by Yash also works.

Change date y-M to Y-m in php

I want to make date from 11-Mar to 2011-03. But I think php is thinking 11-Mar is 2012-Mar-11. How can i do it?
value : 11-Mar
expect : 2011-03
result : 2012-03 [date(strtotime('11-Mar'))]
If you are using PHP >= 5.3.0 Then you can use this...
$date = date_create_from_format('y-M', '11-Mar');
echo date_format($date, 'Y-m');
http://www.php.net/manual/en/datetime.createfromformat.php
You can do this using the DateTime class present in php.
$str = "11-Mar";
$date = DateTime::createFromFormat('y-M', $str);
echo $date->format('Y-m');
http://www.php.net/manual/en/datetime.createfromformat.php
Regards,
$result = date ('Y-m',strtotime('2011-Mar'));
echo $result;
Try
$date= date('Y-m',strtotime('2011 Mar'));
echo $date;
The above is good, this is more exact for what you need to convert FROM:
<?php
$a = "11-Mar";
$date = explode("-", $a);
if ($date[0] <= 99)
$year = '19'.$date[0];
else
$year = '20'.$date[0];
$mon = $date[1];
$date= date('Y-m',strtotime("$year $mon"));
echo $date; // echoes 2011-03
?>

Get the year from specified date php

I have a date in this format 2068-06-15. I want to get the year from the date, using php functions. Could someone please suggest how this could be done.
$date = DateTime::createFromFormat("Y-m-d", "2068-06-15");
echo $date->format("Y");
The DateTime class does not use an unix timestamp internally, so it han handle dates before 1970 or after 2038.
You can use the strtotime and date functions like this:
echo date('Y', strtotime('2068-06-15'));
Note however that PHP can handle year upto 2038
You can test it out here
If your date is always in that format, you can also get the year like this:
$parts = explode('-', '2068-06-15');
echo $parts[0];
I would use this:
$parts = explode('-', '2068-06-15');
echo $parts[0];
It appears the date is coming from a source where it is always the same, much quicker this way using explode.
You can try strtotime() and date() functions for output in minimum code and using standard way.
echo date('Y', strtotime('2068-06-15'));
output: 2068
echo date('y', strtotime('2068-06-15'));
output: 68
public function getYear($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("Y");
}
public function getMonth($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("m");
}
public function getDay($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("d");
}
<?php
list($year) = explode("-", "2068-06-15");
echo $year;
?>
You can achieve your goal by using php date() & explode() functions:
$date = date("2068-06-15");
$date_arr = explode("-", $date);
$yr = $date_arr[0];
echo $yr;
That is it. Happy coding :)
Assuming you have the date as a string (sorry it was unclear from your question if that is the case) could split the string on the - characters like so:
$date = "2068-06-15";
$split_date = split("-", $date);
$year = $split_date[0];
$Y_date = split("-","2068-06-15");
$year = $Y_date[0];
You can use explode also
You wrote that format can change from YYYY-mm-dd to dd-mm-YYYY you can try to find year there
$parts = explode("-","2068-06-15");
for ($i = 0; $i < count($parts); $i++)
{
if(strlen($parts[$i]) == 4)
{
$year = $parts[$i];
break;
}
}

Categories