$this_year = date('Y');
$days_this_year = 365 + date('L');
$day_number = date('z') + 1;
Can I make an array instead of calling date() 3 times? I tried a few times, but could not figure out the syntax I needed
This approach creates a string with the values separated by spaces and explodes it into an array.
$values = date('Y L z');
$items = explode(' ',$values);
echo 'Year: '.$items[0].PHP_EOL;
echo 'Days this year: '.($items[1]+365).PHP_EOL;
echo 'Day number: '.$items[2].PHP_EOL;
Try this
list($this_year,$days_this_year,$day_number) = preg_split("/[\s]/",date('Y L z'));
echo $this_year . PHP_EOL;
echo ($days_this_year + 365) . PHP_EOL;
echo ($day_number + 1) . PHP_EOL;
Probably not the most readable, but just for fun, here's a one-liner:
$array = array_map('array_sum', array_map('array_merge', [[0], [365], [1]], json_decode(date('[[Y],[L],[z]]'), true)));
Related
If current date is 2016-03-06, I would like to get these dates :
2016-03-06
2016-03-05
2016-03-04
2016-03-03
I'm trying to get this purpose but my result not what I want :
$_4date = date("y-m-d",strtotime("day"));
$_3date = date("y-m-d",strtotime("-1 day"));
$_2date = date("y-m-d",strtotime("-2 day"));
$_1date = date("y-m-d",strtotime("-3 day"));
echo $_4date;
echo '<br />';
echo $_3date;
echo '<br />';
echo $_2date;
echo '<br />';
echo $_1date;
the result is :
70-01-01
16-03-05
16-03-04
16-03-03
To get today's date with strtotime, you do strtotime("today");. However, as Bjorn has commented, you can simply just call date() directly.
Furthermore, the reason you are not getting the year in four digits is because you are using a lowercase y instead of an uppercase Y.
Try date("Y-m-d", strtotime("-1 day"));.
The following piece of code illustrates the required changes:
$today = date("Y-m-d");
$yesterday = date("Y-m-d", strtotime("-1 day"));
echo "$today <br />";
echo "$yesterday <br />";
// Output
2016-03-06
2016-03-05
For more informtation, please consult the PHP documentation on the date function. It actually shows you that what to expect from y and Y and it also shows you that the default value that is passed as the second argument is time(), meaning the default is the current time.
PHP's strtotime documentation can be consulted for more information on the strtotime() function and its possible parameters.
Always check the (PHP) documentation first before asking a question.
You need to use like that:
$_4date = date("Y-m-d");
$_3date = date("Y-m-d",strtotime("-1 day"));
$_2date = date("Y-m-d",strtotime("-2 day"));
$_1date = date("Y-m-d",strtotime("-3 day"));
Explanation:
For current date no need to use use strtotime().
For full year you need to use this format Y-m-d.
y-m-d will return you the date 16-03-06 but Y-m-d will return you 2016-03-06.
Use a for loop with strtotime( "... days ago" ):
for( $i = 0; $i < 4; $i++ )
{
echo date( 'Y-m-d', strtotime( "$i days ago" ) ) . PHP_EOL;
}
The first loop (0 days ago) will output today date, other loops will output past days.
3v4l.org demo
You need to use capital 'Y' for full year (2016) instead of small 'y' which will display year in shorthand (16).
And for current date just use date("Y-m-d").
<?php
$_4date = date("Y-m-d");
$_3date = date("Y-m-d",strtotime("-1 day"));
$_2date = date("Y-m-d",strtotime("-2 day"));
$_1date = date("Y-m-d",strtotime("-3 day"));
echo $_4date;
echo '<br />';
echo $_3date;
echo '<br />';
echo $_2date;
echo '<br />';
echo $_1date;
?>
Working Example
<?php
$date = [date("Y-m-d")];
for($i = 1; $i < 4; $i++) {
$date[] = date("Y-m-d",strtotime("-$i day"));
}
//For cli output you'll need:
echo implode("\n", $date) . "\n";
//For web output you'll need:
echo implode("<br />", $date) . "<br />";
I need to find the maximum and minimum date from a given array using PHP.
I have $date_arr which contains following values,
$date_arr = array('0'=>'20-05-2015','1'=>'02-01-2015','2'=>'30-03-2015');
Here, I need to get the larger date as '20-05-2015' and the minimum date as '02-01-2015'.
How can I achieve this?
max() and min() works fine with your array:
echo "Latest Date: ". max($dates)."\n";
echo "Earliest Date: ". min($dates)."\n";
<?php
$date_arr=array(0=>'20-05-2015',1=>'02-01-2015',2=>'30-03-2015');
usort($date_arr, function($a, $b) {
$dateTimestamp1 = strtotime($a);
$dateTimestamp2 = strtotime($b);
return $dateTimestamp1 < $dateTimestamp2 ? -1: 1;
});
echo 'Min: ' . $date_arr[0];
echo '<br/>';
echo 'Max: ' . $date_arr[count($date_arr) - 1];
?>
please Try this
$date_arr = array('0' => '20-05-2015', '1' => '02-01-2015', '2' => '30-03-2015');
for ($i = 0; $i < count($date_arr); $i++)
{
if ($i == 0)
{
$max_date = date('Y-m-d H:i:s', strtotime($date_arr[$i]));
$min_date = date('Y-m-d H:i:s', strtotime($date_arr[$i]));
}
else if ($i != 0)
{
$new_date = date('Y-m-d H:i:s', strtotime($date_arr[$i]));
if ($new_date > $max_date)
{
$max_date = $new_date;
}
else if ($new_date < $min_date)
{
$min_date = $new_date;
}
}
}
echo date('d-m-Y',strtotime($max_date));
echo date('d-m-Y',strtotime($min_date));
Thought it doesn't technically offer the lowest computational time complexity, array_multisort() is a sensible, readable, concise approach. My snippet only calls strtotime() on each element once -- usort() cannot match this claim.
Code: (Demo)
$dates = ['20-05-2015', '02-01-2015', '30-03-2015', '10-01-1990'];
array_multisort(array_map('strtotime', $dates), $dates);
printf(
"Latest Date: %s\nEarliest Date: %s",
$dates[array_key_last($dates)],
$dates[0]
);
Output:
Latest Date: 10-01-1990
Earliest Date: 20-05-2015
To arrive at the same result by calling min() and max(), just create a formatted copy of the dates in unix time.
Code: (Demo)
$unix = array_map('strtotime', $dates);
printf(
"Latest Date: %s\nEarliest Date: %s",
date('d-m-Y', max($unix)),
date('d-m-Y', min($unix))
);
If you want to use usort(), here is the most modern syntax with the spaceship operator and arrow function syntax. (Demo)
usort($dates, fn($a, $b) => strtotime($a) <=> strtotime($b));
printf(
"Latest Date: %s\nEarliest Date: %s",
$dates[array_key_last($dates)],
$dates[0]
);
This task can surely be accomplished tens of different ways. I considered writing a foreach() loop with conditions to maintain temporary variables while making iterated comparisons, but I felt it was prohibitively convoluted for a rather simple task.
$date_arr=array(0=>'2015-05-20',1=>'2015-02-21',2=>'2015-04-13',3=>'2020-04-30',4=>'2020-04-13');
$max_date=$date_arr[0];
for($i=0;$i<count($date_arr);$i++)
{
echo $date_arr[$i]. ' ,';
if( $max_date < $date_arr[$i+1])
{
$max_date=$date_arr[$i+1];
}
}
echo " Max= ". $max_date;
I search for my problem on php.net and on stackoverflow and I did'nt find a good answer to solve my problem, so I decide to ask it !
I have a number of secs :
210
I transform it to 00:03:30 :
gmdate('H:i:s', 210);
But how can I format my answer like :
3m30s or 3min30secs ?
I think I can make this transformation by Exploding my results and concatenate with variable, but I don't know if it's the best solution...
$part = explode(":", $mytime);
$hours = $part[0];
$mins = $part[1];
$secs = $part[2];
$hoursvar = "h";
$minsvar = "m";
$secsvar = "s";
$timefinal = $hours.$hoursvar.$mins.$minsvar.$secs.$secsvar;
Can anyone help me? Thanks.
echo ltrim(date("H", 210), "0")." hours, ".
ltrim(date('i', 210), "0")." min, ".
ltrim(date('s', 210), "0")." secs";
You can format the string inside gmdate, just escape the characters you want to print:
$sec = 210;
echo gmdate("i\m s\s", $sec);
Output:
03m 30s
date() works a little bit like printf(). You pass a format string containing a defined set of meta characters which will be replaced by values. Note that the format string can contain any content not just meta characters. The manual page explains this as well. You can use:
date('i\ms', 210);
You see that you have to escape literals (the m) to that they were not replaced by values.
I hope you can live with a leading zero : 03m30
if not, use:
$date = date('i\ms', 210);
if(strpos($date, '0') === 0) {
$date = substr($date, -strlen($date) + 1);
}
Or, shorter, thanks #Orangepill :) :
$date = ltrim(date('i\ms', 210), '0');
as there is no meta character for minutes without leading zeros known by date().
This is easy, your current date format is H:i:s and you want to convert it to i:s
So you do the following
$date = "00:03:30";
$new_date = date("i_s-",strtotime($date));
Since we can't insert the letters m and s in the function we can use str_replace to replace the _ with m and replace - with s so
$new_date = str_replace("_","m",$new_date);
$new_date = str_replace("-","s",$new_date);
That was the best way I could think of.
$string_time = '00:03:30';
$int_time = strtotime(date('Y-m-d').' '.$string_time);
echo date('i', $int_time).'m'.date('s', $int_time).'s';
$seconds = 210;
$date = gmdate("H\h:i\m:s\s", $seconds);
echo preg_replace('/0([0-9])/','$1', $date);
OUTPUT
0h:3m:30s
You can use gmdate with preg_replace to remove 0 from begining.
OR more advanced
$seconds = 210;
$date = gmdate("H\h:i\m:s\s", $seconds);
$match = array('/0([0-9])/','/s/','/m\:/','/h\:/');
$replace = array('$1', ' sec ', ' min ', ' hours ');
echo preg_replace($match,$replace, $date);
OUTPUT:
0 hours 3 min 30 sec
echo ltrim(date("H", 210), "0")." hours, ".
ltrim(date('i', 210), "0")." min, ".
ltrim(date('s', 210), "0")." secs";
Thanks to Orangepill !
I am getting from Facebook Graph API the last 3 months page views information from all the accounts that I am admin with the following method:
$since_date = date('Y-m-d', strtotime('-3 months'));
$until_date = date('Y-m-d');
$page_views = $facebook->api('/' . $account['id'] . '/insights/page_views?since=' . $since_date . '&until=' . $until_date . '','GET');
After that I am using a php foreach loop (actually two) to get the desired information (page views and the date) in a required format (an array) like this:
foreach ($page_views['data'] as $page_view) {
$i = 0;
$len = count($page_view['values']);
foreach($page_view['values'] as $key => $page_view_values) {
$end_time = strval($page_view_values['end_time']);
$value = intval($page_view_values['value']);
echo '[\'' . substr($end_time, 0, -14) . '\', ' . $value . ']';
if ($i == $len - 1) {
continue;
} else {
echo ', ';
}
$i++;
}
Which output for further needs the following array:
(.....],['2013-04-02', 21], ['2013-04-03', 7], ['2013-04-04', 2], ['2013-04-05', 0], ['2013-04-06', 2], ['2013-04-07', 3], ['2013-04-08', 1], ['2013-04-09', 2], ['2013-04-10', 5], ['2013-04-11', 1], ['2013-04-12', 11], ['2013-04-13', 0],[.....)
All is working like it should, with the above array. I render a very nice chart but I want to filter it if I could based on days of the week. For exemple: I want an array like the one above with only the dates from Monday or Tuesday and so on... I need to filter somewhere in the second php foreach to return only the days that I want but how? What condition is used for this kind of needs? Or I should use other method, for example, query something else from the Facebook Graph Api? Any guidance is more than welcomed.
You could do for example a switch case based on the 3-letter code of the week day, and do something like this for each day:
$tempDate = '2012-07-10';
echo date('D', strtotime( $tempDate));
It will output: Tue
This will allow you to filter by the week day. For example, you would only add to the array if the weekday code is Tue. All others will be skipped.
Added #arraintxo note:
date('N', strtotime($tempDate))
would return a numeric value of the week day (1 to 7, 1 being Monday and 7 Sunday), easier to compare.
I'd suggest something similar to the current reply, with slight adjustments:
$first=false; $cache=array(); $conv=new \Date('2000-01-01T00:00:00Z');
foreach ($page_views['data'] as $page_view) {
foreach($page_view['values'] as $key => $page_view_values) {
$end_time = strval($page_view_values['end_time']);
$ds=substr($end_time, 0, -14);
$value = intval($page_view_values['value']);
if(!isset($cache[$ds])
$cache[$ds]=(int)$conv->modify($ds)->format('N');
if($first){ echo ', '; $first=false; }
echo '[\'' . $ds . '\', ' . $value . ', '.$cache[$ds].']';
}
}
The day indices are now present as the third items of the arrays. Notice 1: a cache is used so that you look up every date only once. Notice 2: using a bool to not add leading separators is much cheaper than counting down from a count which is in turn cheaper than counting up to a count (what you did in the first place). Notice 3: This modifies the $conv object again and again, because I don't like creating many objects, and this ought to perform at least as well as the procedural style (date() and strtotime()).
In the first place I want to thank you all for the prompt replies, it was a great help received and I am very grateful for it. Based on your guidelines I solve my "issue" in the following manner:
$since_date = date('Y-m-d', strtotime('-3 months'));
$until_date = date('Y-m-d');
$page_views = $facebook->api('/' . $account['id'] . '/insights/page_views?since=' . $since_date . '&until=' . $until_date . '','GET');
foreach ($page_views['data'] as $page_view) {
$i = 0;
foreach($page_view['values'] as $key => $page_view_values) {
$end_time = strval($page_view_values['end_time']);
$ds = substr($end_time, 0, -14);
$value = intval($page_view_values['value']);
if (date('N', strtotime($ds)) != 1) {
continue;
} else {
if ($i==1) {
echo ', ';
}
$i=1;
echo '[\'' . $ds . '\', ' . $value . ']';
}
}
}
I can do this for every day of the week by using date('N', strtotime($ds)) for the corresponding number of the day. I receive the array that I want but if I can, i want to know if is possible to sum the numbers in the variables called $page_view_values['value'] (i want to make a comparison between the days in the week).
How do I get the "UTC, PST, EST, etc.." name from this time offset?
You can copy/paste this in any PHP file and it will run.
<?php
date_default_timezone_set('UTC');
$time = '2012-01-01T21:15:00+00:00';
echo '<pre>';
echo "<b>Step 1 (Have the date now)</b>\n";
$time = explode('T', $time);
print_r($time);
echo "\n\n<b>Step 2 (Get the offset)</b>\n";
$offset = explode('+', $time[1]);
$time[1] = $offset[0];
print_r($offset);
echo "\n\n";
echo date('l F jS', strtotime($time[0])) . ', at ' . date('g:ia', strtotime($time[1]));
echo "\n\n";
//
// How do I matchup the offset in this list?
// The values are -18000, -7200
//
$b = timezone_abbreviations_list();
print_r($b);
Note: I've also tried using echo date('c', $time); but perhaps I have something wrong its giving me an error.
In PHP 5.1.0+ echo date('e', $time); will return the timezone information.