I'm trying to make a function that formats dates from nested arrays lying in the same array. I'm able to locate and echo the values in the array, however I'm struggling to format the date into the way I want to print it out. The way my code is set up I have one function that goes into the array, iterates over each of the nested arrays and prints out the value attached to the key that it is set to look for.
That works fine, but my other function is meant to take the date and format it into the way I wish it to print out with the date function and just no go. I've got a few ideas as to why this is the case, but I know I don't know which is why I'm hoping someone can help. Thanks in advance, I appreciate anyone trying to help me on this. I'm new to php so it's been an interesting foray.
I've used the php date, strtotime, and date_create_from_format functions to attempt to take the date and format it into a date the way I want to.
// Example clip from array
$Full_List_Of_Recover_Items = array (
0 =>
array (
'ActionTimeStamp' => '2018-07-23 15:17:23'
)
);
// End format would look like July 23, 2018 3:17pm
<?php
function valGet($arr, $value)
{
foreach($arr as $row)
{
foreach($row as $key => $val)
{
if ($key == $value)
{
if ($val == NULL)
echo "empty";
else
echo $val;
}
}
}
}
function timeFormat($timeStamp)
{
// split the array value to set up date
$first = explode(" ", $timestamp);
$second = explode("-", $first);
$third = explode(":", $second);
// format the date and convert it attempt
$stringTime = strtotime("D, F, d, Y, g, i", $timestamp);
$date = date_create_from_format("Y-m-d H:i:s");
echo date($date($stringTime));
}
?>
// invocation on html
<p>
<?php
echo timeFormat(valGet($Full_List_Of_Recover_Items, 'ActionTimeStamp'));
?>
</p>
You need to modify your timeFormat function. Just use strtotime:
$timeStamp = '2018-07-23 15:17:23';
echo date("F j, Y, g:i a", strtotime($timeStamp)); // prints July 23, 2018, 3:17 pm
And here you can see the documentation for all kind of format: PHP manual date
Reference: strtotime
Related
Right now my program echo an array of dates generated with for loop. What I'm trying to do is echo dates individually.
Initial code
// initialize an array with your first date
$dates = array(strtotime("+11 days", strtotime("2017-09-04")));
for ($i = 1; $i <= 5; $i++) {// loop 5 times to get the next 5 dates
// add 7 days to previous date in the array
$dates[] = strtotime("+7 days", $dates[$i-1]);
}
// echo the results
foreach ($dates as $date) {
echo date("Y-m-d", $date);
echo "<br>";
}
Initial Output
2017-09-15
2017-09-22
2017-09-29
2017-10-06
2017-10-13
What I have tried
echo $dates[0];//print first date
echo "<br>";
echo $dates[1];//print second date
Trial Output
1505426400
1506031200
How can I achieve this?
Either you need to use date() when outputting the elements as well - as they still are timestamps in the array (you don't change anything in the loop, you just print the elements), or you need to change the elements when you loop over them.
Alternative 1: Format on output
Convert from timestamp to datestring on output. This will still have timestamps in the array.
echo date("Y-m-d", $dates[0]);
Alternative 2: Alter the elements in the array
Alternatively, you can alter the value in the array when you loop it through foreach. If you pass by reference, you can change the value of the element inside the loop, by using & (which means that the variable is a reference and not a copy). This means that you now have datestrings in the array, and not timestamps.
foreach ($dates as &$date) {
echo $date = date("Y-m-d", $date);
echo "<br>";
}
If you pass by reference, you can now print it directly, as it will no longer contain the timestamp, since we changed it to the datestring.
echo $dates[0];
You should only adapt one of the alternatives, whichever is most suitable for your application.
PHP.net "Passing by Reference"
try this
echo date("Y-m-d", ($dates[0])) . '<br>';
echo date("Y-m-d", ($dates[1])) . '<br>';
I have several dates, some of the past, some of the future, and I want to show only the next date in the future of this list. If there is no date in the future, I want to echo some text.
I am using ACF Date Picker inside a Repeater. First of all, I think I have to get the current date, to compare it with the others:
date_default_timezone_set('Europe/Berlin');
$date = date('Ymd', time());
I chose the Ymd format because the repeater outputs the dates the exact same way. Now I need to check somehow all subfields inside my repeater. I guess this is done using somehow like
$rows = get_field('repeater_field_name');
if($rows) {
foreach($rows as $row) {
// compare the dates, choose only the next coming date
// dates are stored in the_sub_field('repeater_date_field');
}
}
How can I get all the_sub_field('repeater_date_field') of my get_field('repeater_field_name') values? And how can I detect its row (for adding other sub fields to the same row)?
You can store your all dates in array. Then sort it in ascending order. Then take the first date from the list which is greater than today.
Please look into below code.
date_default_timezone_set('Europe/Berlin');
$date = date('Ymd', time());
$dates = array();
$rows = get_field('repeater_field_name');
if($rows) {
foreach($rows as $row) {
$dates[] = $row->date_field;
// compare the dates, choose only the next coming date
// dates are stored in the_sub_field('repeater_date_field');
}
}
sort($dates);
$final_date = "";
foreach($dates as $date_row){
if($date_row > $date){
$final_date = $date_row;
return true;
}
}
echo $final_date;
You can compare 2 date to solve this problem. For example
$date_bef = strtotime("151218"); // December 18, 2015
$date_after = strtotime("151219"); // December 19, 2015
if($date_after - $date_bef == 1)
echo "This is a next day";
If you don't want compare, you can add 1 day to existing time, example
$next_day = date("Ymd",strtotime("151220") + 60*60*24);
I am working with arrays of values in PHP. Some of these values may include a date in various string formats.
I need to convert dates in multiple formats to their numerical equivalent (Unix timestamp). The problem is being able to determine if the string is a date.
Using
if (($timestamp = strtotime($str)) === false)
will check for a valid date from a string but how do I determine if the value should even be validated as a date?
Example:
$x = {1,2,3,"4","11/12/2009","22/12/2000",true,false};
foreach($x as $value)
{
if(is_bool($value))
if(is_string($value))
if(is_numeric($value))
if(is_date($value)) ?
...
}
In short, is there an easy way to check if a string value is a date?
In short, is there an easy way to check if a string value is a date?
Not really, seeing as it could be in an arbitrary format.
If at all possible, I would tend to leave parsing to the magic of strtotime(). If it manages to create a valid date, fine. If it doesn't, you'll receive false.
Be prepared for the possibility of false positives, though, because strtotime() parses even things like "Last Friday".
If strtotime() is too liberal for you, you could consider building a collection of date formats you want to accept, and run PHP 5.3's DateTime:createFromFormat using every one of the formats on every date.
Something like (untested)
$formats = array("d.m.Y", "d/m/Y", "Ymd"); // and so on.....
$dates = array(1,2,3,"4","11/12/2009","22/12/2000",true,false);
foreach ($dates as $input)
{
foreach ($formats as $format)
{
echo "Applying format $format on date $input...<br>";
$date = DateTime::createFromFormat($format, $input);
if ($date == false)
echo "Failed<br>";
else
echo "Success<br>";
}
}
The problem with Pekka's script is that the date '2011-30-30' is also considered valid. This is the modified version.
$formats = array("d.m.Y", "d/m/Y", "Ymd"); // and so on.....
$dates = array(1,2,3,"4","11/12/2009","22/12/2000",true,false);
foreach ($dates as $input)
{
foreach ($formats as $format)
{
echo "Applying format $format on date $input...<br>";
$date = DateTime::createFromFormat($format, $input);
if ($date == false || !(date_format($date,$format) == $input) )
echo "Failed<br>";
else
echo "Success<br>";
}
}
Extrapolating from http://au1.php.net/checkdate#113205 ;
just change the $formats array to all the formats you want to check.
public function convertDate($value) {
$formats = ['M d, Y', 'Y-m-d'];
foreach($formats as $f) {
$d = DateTime::createFromFormat($f, $value);
$is_date = $d && $d->format($f) === $value;
if ( true == $is_date ) break;
}
return $is_date;
}
I'm having date 20/12/2001 in this formate . i need to convert in following format 2001/12/20 using php .
$var = explode('/',$date);
$var = array_reverse($var);
$final = implode('/',$var);
Your safest bet
<?php
$input = '20/12/2001';
list($day, $month, $year) = explode('/',$input);
$output= "$year/$month/$day";
echo $output."\n";
Add validation as needed/desired. You input date isn't a known valid date format, so strToTime won't work.
Alternately, you could use mktime to create a date once you had the day, month, and year, and then use date to format it.
If you're getting the date string from somewhere else (as opposed to generating it yourself) and need to reformat it:
$date = '20/12/2001';
preg_replace('!(\d+)/(\d+)/(\d+)!', '$3/$2/$1', $date);
If you need the date for other purposes and are running PHP >= 5.3.0:
$when = DateTime::createFromFormat('d/m/Y', $date);
$when->format('Y/m/d');
// $when can be used for all sorts of things
You will need to manually parse it.
Split/explode text on "/".
Check you have three elements.
Do other basic checks that you have day in [0], month in [1] and year in [2] (that mostly means checking they're numbers and int he correct range)
Put them together again.
$today = date("Y/m/d");
I believe that should work... Someone correct me if I am wrong.
You can use sscanf in order to parse and reorder the parts of the date:
$theDate = '20/12/2001';
$newDate = join(sscanf($theDate, '%3$2s/%2$2s/%1$4s'), '/');
assert($newDate == '2001/12/20');
Or, if you are using PHP 5.3, you can use the DateTime object to do the converting:
$theDate = '20/12/2001';
$date = DateTime::createFromFormat('d/m/Y', $theDate);
$newDate = $date->format('Y/m/d');
assert($newDate == '2001/12/20');
$date = Date::CreateFromFormat('20/12/2001', 'd/m/Y');
$newdate = $date->format('Y/m/d');
I got a code like this that works just fine.
$dates[] = date('F, Y', $date);
I wonder if it's possible to pass a variable to the first argument. Something like this (but this doesn't work):
$date_format = 'F, Y';
$dates[] = date($date_format, $date);
EDIT: This actually works just fine. Just placed the variable in the wrong place.
That's perfectly legal. As to why it doesn't work, can you provide a code snippet that doesn't work? There will be some other reason why. I run this:
$date_format = 'F, Y';
$inputs = array(time(), time() + 5000000, time() + 10000000);
$dates = array();
foreach ($inputs as $input) {
$dates[] = date($date_format, $input);
}
print_r($dates);
and get:
Array
(
[0] => November, 2009
[1] => January, 2010
[2] => March, 2010
)
date() just takes a string as it's first argument. Whether it is a literal string like your first example or a variable containing a string like the second example doesn't matter - they are equivilent.
I try your code, no problem for me.
Are you sure that your date is a time ? with the function time for example ?