Format php date with a variable - php

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 ?

Related

checkdate doesn't work correctly when given variables instead of literals

The following code:
$date = "1-1-2021";
list($year, $month, $day) = explode("-", $date);
$check = checkdate($month, $year, $date);
echo "$check";
Doesn't output anything. When I try running this script instead of outputting true/false, it just outputs nothing. Where as:
$check2 = checkdate(1, 1, 2021);
echo "$check2";
Outputs 1, which, if I'm not mistaken, means false. Therefore the input given in the second code block is also incorrect.
What am I doing wrong here? Why does the first not output anything, and the second outputs false?
Edit: It seems that in fact 1 is true. Therefore the second block produces the expected result; I'm therefore led to believe that something is wrong with $year, $month or $day, but since they hold the values of 2021, 1 and 1 I'm struggling to see the issue here.
$date = "1-1-2021";
list($day,$month,$year) = explode("-", $date);
$check = checkdate($month, $day, $year);
echo "$check";
The PHP list() function will generate an array based on the explode() result.
The first position of the array is the day, the second position is the month and the third position is the year. So the list looks like this:
list($day,$month,$year) = explode("-", $date);
To check if it is a valid date using the checkdate() function you must pass the month in the first position, the day in the second position and the year in the third position.
You will receive an response:
0 = invalid date
1 = valid date

Php format an array of dates

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

Numeric value of Months in PHP

Im trying to display my Date field from my MySQL database.
format is 2012-01-01 to 2012-01-31
Is there a way to display the month of January to 0 instead of 1?
I used strtotime to change its format
date('Y, n, j',strtotime($s['date']))
but this showed
2012, 1, 1
I want to display this as
2012, 0, 1
You can always do something like:
$time = strtotime($s['date']);
$str = date('Y, ', $time);
$str .= intval(date('n', $time)) - 1;
$str .= date(', j', $time);
Not sure this is the best/only way, but it should work.
EDIT: davidethell's point taken, code changed accordingly. +1 for the comment.
Or you could use getdate() instead of date() to return the date as an array, and then concatenate the required values eg.
<?php
$date = getDate(strtotime($s['date']));
echo $date['year'].', '.($date['mon']-1).', '.$date['mday'];
?>
If you prefer you can do it in SQL:
SELECT MONTH(my_date_col) - 1 AS custom_month_col;
Otherwise I agree with #Ynhockey
Edited (see comment):
SELECT CONCAT(YEAR('2012-03-08'),'-', (MONTH('2012-03-08') - 1), '-', DAY('2012-03-08')) AS custom_month_col;
In case you only need the month output, this worked for me:
$month = intval(date('n',strtotime($result["Date"]))) - 1;
$result["Date"] is how the value passed from MySQL is called.

strtotime and then convert to UNIX?

EDIT
Per the comment below, here's my attempt at splitting / combining / converting the string prior to implementing mktime...
$date1 = explode("T",'2005-03-27T00:00:00');
$date2 = explode("-", $date1[0]);
$try = mktime($time1,$time2,0,$date2[1],$date[2],$date[3]);
print $try;
// Prints out: 951793200
Original Question:
I've inherited a database and would like very much to convert the bizarre way the data is stored to something more mysql-friendly...
In the meantime, I get a text string (yes... text)... That I'd like to convert to unixtime...
So, I'll get a string that looks like this:
2005-03-27T00:00:00 03:00 AM
I'd like to convert it to:
1111885200
Dates and times always mess me up... I've done a number of things using strtotime and mktime, but can't get it formatted the way I want.
Well, this is how I would do it.
$ex = '2005-03-27T00:00:00 03:00 AM';
$format = '%Y-%m-%dT00:00:00 %H:%M %p';
$strf = strptime($ex, $format);
$date_str = $strf['tm_mon'] + 1 . '/' . $strf['tm_mday'] . '/' . ($strf['tm_year'] + 1900) . ' ' . $strf['tm_hour'] . ':' . $strf['tm_min'] . ':00';
echo $date_str;
echo "\n";
echo strtotime($date_str);
echo "\n";
echo date('m-d-Y H:i:s', 1111885200);
But, your desired result does not seem to be correct based on the date you posted.
OUTPUT
3/27/2005 3:0:00
1111921200
03-26-2005 17:00:00
You could write a litte converter script that does the task for you.
Please check the optional parameters of mktime
You could try to split your string in hour / minute / second / month / day / year and put that into mktime. Then mktime will give you the unix timestamp for that.
So, I'm not a fan of regular expressions unless absolutely necessary, but they might be necessary here to pick out the time zone piece.
preg_match("/(\d{4})-(\d{2})-(\d{2})(T\d{2}:\d{2}:\d{2}) (\d{2}:\d{2}) (AM|PM)/", '2005-03-27T00:00:00 03:00 AM',$matches);
Will give you $matches that look something like:
Array
(
[0] => 2005-03-27T00:00:00 03:00 AM
[1] => 2005
[2] => 03
[3] => 27
[4] => T00:00:00
[5] => 03:00
[6] => AM
)
I would feed those pieces into a DateTime object. Then you can output it into any format you want. You also may have to adjust that regex some so it can handle all your dates.
If the T00:00:00 part is useless, just remove it and use strtotime():
<?php
$date = '2005-03-27T00:00:00 03:00 AM';
$timestamp = strtotime(preg_replace('!T[^ ]+!', '', $date));
var_dump(date('d/m/Y H:i:s', $timestamp));
?>
This prints:
string(19) "27/03/2005 03:00:00"

change dd/mm/yy date format to yy/mm/dd using php

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');

Categories