PHP array question - php

I was wondering how can I turn the following date into an array.
PHP code.
$current_date = date('Y-m-d H:i:s'); //current date

$current_date = array(date('Y-m-d H:i:s'));

The built-in php function strptime() converts a date to an array. See the linked documentation for details about the structure of the array it produces.

I think you want to get the components of the function return into an array.
// Method one
$current_date = array(date('Y'),date('m'),date('d'),date('H'),date('i'),date('s'));
// Method two
$current_date = date('Y-m-d H:i:s'); //current date
$exploded_current_date = explode(" ", $current_date);
$date = explode("-",$exploded_current_date[0]);
$time = explode(":",$exploded_current_date[1]);
$current_date = array_merge($date,$time);
Update:
// Method three
$current_date = getdate();
/*
Returns
Array
(
[seconds] => 40
[minutes] => 58
[hours] => 21
[mday] => 17
[wday] => 2
[mon] => 6
[year] => 2003
[yday] => 167
[weekday] => Tuesday
[month] => June
[0] => 1055901520
)
*/

Here is an example.
<?php
$format = '%d/%m/%Y %H:%M:%S';
$strf = strftime($format);
echo "$strf\n";
print_r(strptime($strf, $format));
?>

Related

Add 3 month to the given date in a loop PHP

Hi i have the following date = 2015-06-01 00:00:00
so i have to add 3 month to this date , so write the following code
$sarting="2015-06-01 00:00:00";
$date[$i]=date('Y-m-d', strtotime($sarting . "+3 months") );
And i get the output = 2015-09-01;
But now i want to add 3 month again and again for 20 times and i have to store the output to array
so i write the following code
$store_date=array();
for($i=0;$i<20;$i++){
$store_date[$i]=date('Y-m-d', strtotime($sarting . "+3 months") );
}
But the thing it's returning 2015-09-01 20 times . i need like this 2015-09-01, 2015-12-01,2016-06-01 etc .
Please check
I would recommend using the DateTime-class so we can reuse the same instance on each iteration.
$sarting = "2015-06-01 00:00:00";
$store_date = [];
// Create a DateTime-object we can reuse
$date = new DateTime($sarting);
for ($i = 0; $i < 20; $i++) {
$date->modify('+3 months');
$store_date[] = $date->format('Y-m-d');
}
print_r($store_date);
Since we're resuing the same object, it will keep adding 3 months to it on each iteration. No need for any calculations or anything, making the code clean and readable.
Demo: https://3v4l.org/KZiH9
You can use PHP's dateTime class' modify() method to add +3 months in loop to it.
<?php
$dateStamp = "2015-06-01 00:00:00";
$date = new DateTime($dateStamp);
$datesArr = [];
for ($i=1; $i<21 ; $i++) {
$date->modify('+3 month');
$datesArr[] = $date->format('Y-m-d h:i:s');
}
echo '<pre>';
print_r($datesArr);
echo '</pre>';
Output:
Array
(
[0] => 2015-09-01 12:00:00
[1] => 2015-12-01 12:00:00
[2] => 2016-03-01 12:00:00
[3] => 2016-06-01 12:00:00
[4] => 2016-09-01 12:00:00
[5] => 2016-12-01 12:00:00
[6] => 2017-03-01 12:00:00
[7] => 2017-06-01 12:00:00
[8] => 2017-09-01 12:00:00
[9] => 2017-12-01 12:00:00
[10] => 2018-03-01 12:00:00
[11] => 2018-06-01 12:00:00
[12] => 2018-09-01 12:00:00
[13] => 2018-12-01 12:00:00
[14] => 2019-03-01 12:00:00
[15] => 2019-06-01 12:00:00
[16] => 2019-09-01 12:00:00
[17] => 2019-12-01 12:00:00
[18] => 2020-03-01 12:00:00
[19] => 2020-06-01 12:00:00
)
Working Code:
You are not changing the value of $sarting. Try this:
$sarting = "2015-06-01 00:00:00";
$store_date = array();
for ($i = 0; $i < 20; $i++) {
$sarting = $store_date[$i] = date('Y-m-d', strtotime($sarting . "+3 months"));
}
Try this check if it helps,
$sarting="2015-06-01 00:00:00";
$store_date=array();
for($i=0;$i<20;$i++){
$store_date[$i]=date('Y-m-d', strtotime($sarting . "+3 months") );
$sarting=$store_date[$i];
}
echo "<pre>";
print_r($store_date);
echo "</pre>";
Below code for Addition or Subtraction for Year/Month/day from date
Addition = date('Y-m-d', strtotime("+0 years +3 months +0 days", strtotime($lastdate)));
Subtraction = date('Y-m-d', strtotime("+0 years -3 months +0 days", strtotime($lastdate)));
$lastdate = "01-12-2015"; //actual date
$after_3_month = date('Y-m-d', strtotime("+0 years +3 months +0 days", strtotime($lastdate))); // adding 3 month on the actual date
echo $after_3_month; //3 month added with actual date

Stuck at date-format in seconds

first of all, I'm sorry for my english. I'm from germany.
Now my Problem:
I have a multiple array with some dates in it. I had to filter the first and the last date for every IP because I need the difference of both dates to know how much time the User on my website.
I did that and got all I need. Here is a part of my code output:
$ip_with_dates:
Array
(
[0] => Array
(
[ip] => 72.xx.xx.xx
[first_date] => 2015-10-12 00:10:15
[last_date] => 2015-10-12 01:10:51
)
[1] => Array
(
[ip] => 85.xx.xx.xx
[first_date] => 2015-10-12 00:10:19
[last_date] => 2015-10-12 01:10:56
)
I tried to get the time between those two dates with:
$visit_lenght = [];
foreach($ip_with_date as $key => $val){
$date1 = new DateTime($val['first_date']);
$date2 = new DateTime($val['last_date']);
$interval = $date1->diff($date2)->format('%h %m %s');
$visit_lenght[] = $interval;
}
what gives me this output:
Array
(
[0] => 1 36
[1] => 1 37
[2] => 0 3
[3] => 0 9
)
well but this isn't good to work with. I need the time in seconds not in H:m:s
but I really don't now how. This is a part of my project where I'm really fighting with. Maybe someone of you could help me with this.
I'm working with laravel. Normal PHP would make it too but if someone knows a solution in laravel, it would be nice as well!
thanks for any help!
To get time diff in seconds you need to convert your datetime objects to timestamps:
$visit_lenght = [];
foreach($ip_with_date as $key => $val){
$date1 = new DateTime($val['first_date']);
$date2 = new DateTime($val['last_date']);
$interval = $date1->getTimestamp() - $date2->getTimestamp()
$visit_lenght[] = $interval;
}
You may get timestamps of two dates and count the difference.
something like (in php).
$date1t = $date1->getTimestamp();
$date2t = $date2->getTimestamp();
$diff = $date2t - $date1t;
http://php.net/manual/en/datetime.gettimestamp.php
Try this way (general/basic way)
$visit_lenght = [];
foreach($ip_with_date as $key => $val){
$date1 = strtotime($val['first_date']);
$date2 = strtotime($val['last_date']);
//$interval = $date1->diff($date2)->format('%h %m %s');
$interval = $date2 - $date1;
$visit_lenght[] = $interval;
}
you can make this:
->format('Y-m-d H:i:s')
With DateTime() class of PHP, it is super simple to find difference between time. Here is an exmple:
<?php
$ip = "xxxx-xxx-xxx";
$t1 = DateTime::createFromFormat('Y-m-d H:i:s', '2015-10-12 00:10:15');
$t2 = DateTime::createFromFormat('Y-m-d H:i:s', '2015-10-12 01:10:51');
echo "User from IP {$ip} spent " . $t1->diff($t2)->format("%h hours, %i minutes and %s seconds");
?>

Convert local date time to UTC date time

When user enters Date and time using 'input type=date name="date"' && 'input type=time name="time"' tags according to his/her timezone,
for eg :- If a user from India, (Asia/Kolkata) timezone entered a date : 1/22/14 and time : 5:30pm , I need to Convert it into UTC time stamp for storing it to DB, To Achive that
I used below code:-
$year=substr($date,0,4);
$month=substr($date,5,2);
$day=substr($date,8);
$hour=substr($time,0,2);
$minute=substr($time,3);
$clientzone=mysql_result(mysql_query("select timezone from c_users_extra where c_id='{$_SESSION['clientid']}'"),0,0); //Fetches the timezone of user
date_default_timezone_set($clientzone);//Setting default timezone to client timezone
$datetime = new DateTime("$year-$month-$day $hour:$minute:00");
$la_time = new DateTimeZone('UTC');
$datetime->setTimezone($la_time);
$values=$datetime->format('Y-m-d H:i:s');
$year=substr($values,0,4);
$month=substr($values,5,2);
$hour=substr($values,11,2);
$minutes=substr($values,14,2);
$seconds=substr($values,17,2);
$timestamp=mktime($hour,$minutes,$seconds,$month,$day,$year);//creating new timestamp from coverted
print_r(getdate($timestamp));//Result : Array ( [seconds] => 0 [minutes] => 30 [hours] => 6 [mday] => 22 [wday] => 3 [mon] => 1 [year] => 2014 [yday] => 21 [weekday] => Wednesday [month] => January [0] => 1390372200 )
//Expected Result : Array ( [seconds] => 0 [minutes] => 0 [hours] => 12 [mday] => 22 [wday] => 3 [mon] => 1 [year] => 2014 [yday] => 21 [weekday] => Wednesday [month] => January [0] => 1390372200 )
Why I get this wrong time stamp ?
Here is an object oriented example:
<?php
$date = '2014-01-22 18:15:00'; // assumed date is formatted correctly
$clientzone = 'America/New_York'; // assumed timezone is a valid one from your SQL
$dateObj = new DateTime($date, new DateTimeZone($clientzone));
echo "Original: " . $dateObj->format('Y-m-d H:i:sP') . "\n";
$dateObj->setTimezone(new DateTimeZone('UTC')); // convert to UTC
echo "Converted: " . $dateObj->format('Y-m-d H:i:sP') . "\n";
echo "Epoch: ".$dateObj->format('U');
?>
You can format that just like the date function.
The $date and $clientzone are assumed to be valid.
Can't you do something simpler like:
$user_time = strtotime($date);
$dateTimeZone = new DateTimeZone($timezone);
// get the offset from server time (UTC)
$tzOffset = $dateTimeZone->getOffset(new DateTime());
$result_time = $user_time - $tzOffset;
Try following function to convert Local date time to UTC date time
function LocaltoUTC($date_to_convert)
{
$local_timestamp = strtotime($date_t);
$UTC_timestamp += ((-(5.5)) * 3600); // 5.5 is UTC timezone or local timezone
$gmt_datetime = gmdate('y-m-d H:i:s', $UTC_timestamp);
return $gmt_datetime;
}
Here is a similar question. Take a look at Adjusting time zone in PHP with DateTime / DateTimeZone
There is a solution and a more comfortable way to do your task.

Find week days date from range of the two dates

$start_date = "2013-05-01";
$last_date = "2013-08-30";
How can I get dates of tuesdays and thursdays between these two dates?
<?php
$start = new DateTime('2013-05-01');
$end = new DateTime('2013-08-30');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
if ($dt->format("N") == 2 || $dt->format("N") == 4) {
echo $dt->format("l Y-m-d") . "<br>\n";
}
}
See it in action
What this code does:
Creates a starting date object using DateTime.
Creates a starting date object using DateTime.
Creates a DateInterval object to represent our interval of time to iterate through. In this case 1 day.
Creates a DatePeriod object to manage these objects.
Using DatePeriod, it iterates through the date starting with the starting date and ending at the end date. We use DateTime::format() with the N parameter to get the day number of the week. If the day number of the week is 2 (Tuesday) or 4 (Thursday) echo out it's value.
Some PHP-Fu
$start_date = '2013-05-01';
$last_date = '2013-08-30';
$dates = range(strtotime($start_date), strtotime($last_date),86400);
$days = array('tuesday' => array(), 'thursday' => array());
array_map(function($v)use(&$days){
if(date('D', $v) == 'Tue'){
$days['tuesday'][] = date('Y-m-d', $v);
}elseif(date('D', $v) == 'Thu'){
$days['thursday'][] = date('Y-m-d', $v);
}
}, $dates); // Requires PHP 5.3+
print_r($days);
Output
Array
(
[tuesday] => Array
(
[0] => 2013-05-07
[1] => 2013-05-14
[2] => 2013-05-21
[3] => 2013-05-28
[4] => 2013-06-04
[5] => 2013-06-11
[6] => 2013-06-18
[7] => 2013-06-25
[8] => 2013-07-02
[9] => 2013-07-09
[10] => 2013-07-16
[11] => 2013-07-23
[12] => 2013-07-30
[13] => 2013-08-06
[14] => 2013-08-13
[15] => 2013-08-20
[16] => 2013-08-27
)
[thursday] => Array
(
[0] => 2013-05-02
[1] => 2013-05-09
[2] => 2013-05-16
[3] => 2013-05-23
[4] => 2013-05-30
[5] => 2013-06-06
[6] => 2013-06-13
[7] => 2013-06-20
[8] => 2013-06-27
[9] => 2013-07-04
[10] => 2013-07-11
[11] => 2013-07-18
[12] => 2013-07-25
[13] => 2013-08-01
[14] => 2013-08-08
[15] => 2013-08-15
[16] => 2013-08-22
[17] => 2013-08-29
)
)
Online demo
$start_date = strtotime("2013-05-01");
$last_date = strtotime("2013-08-30");
while ($start_date <= $last_date) {
$start_date = strtotime('+1 day', $start_date);
if (date('N',$start_date) == 2 || date('N',$start_date) == 4){
echo date('Y-m-d', $start_date).PHP_EOL;
}
}
<?php echo date('Y-m-d', strtotime('next thursday', strtotime($start_date)));
Also for tuesday ofcourse
Please use the following function for your solution,
function daycount($day, $startdate, $lastdate, $counter=0)
{
if($startdate >= $lastdate)
{
return $counter;
}
else
{
return daycount($day, strtotime("next ".$day, $startdate), ++$counter);
}
}
$start_date = "2013-05-01";
$last_date = "2013-08-30";
echo "Tuesday Count - ".daycount("tuesday", strtotime($start_date), strtotime($last_date));
echo "<br/>";
echo "Thursday Count - ".daycount("thursday", strtotime($start_date), strtotime($last_date));
Try with this
$startDate = strtotime($start_date);
$endDate = strtotime($last_date);
while ($startDate < $endDate) {
echo date('Y-m-d', $startDate ). "\n";
// Give the condition to find last Tuesday
$startDate = strtotime( 'next Tuesday', $startDate );
}
With DateTime:
$start_date = "2013-05-01";
$last_date = "2013-08-30";
$start = new DateTime($start_date);
$clone = clone $start;
$start->modify('next thursday');
$thursday=$start->format('Y-m-d');
$clone->modify('next tuesday');
$tuesday=$clone->format('Y-m-d');
echo $thursday; //2013-05-02
echo $tuesday; //2013-05-07
We need to objects because if in interval tuesday is before thursday we will have next tuesday. But you can modify little code to use one object.
With the help of few php date functions this can be solved easily..
<?php
// Create the from and to date
$start_date = strtotime("2013-05-01");
$last_date = strtotime("2013-08-30");
// Get the time interval to get the tue and Thurs days
$no_of_days = ($last_date - $start_date) / 86400; //the diff will be in timestamp hence dividing by timestamp for one day = 86400
$get_tue_thu_days = array();
// Loop upto the $no_of_days
for($i = 0; $i < $no_of_days; $i++) {
$temp = date("D", $start_date);
if($temp == "Tue" || $temp == "Thu") {
$get_tue_thu_days[] = date("D/M/Y", $start_date); //formating date in Thu/May/2013 formate.
}
$start_date += 86400;
}
print_r($get_tue_thu_days);
if you have a reference date which you know is a tuesday/thursday you can find days which are a multiple of 7 days from your reference date, these days will always be the same day of the week.

how to re-format datetime string in php?

I receive a datetime from a plugin. I put it into a variable:
$datetime = "20130409163705";
That actually translates to yyyymmddHHmmss.
I would need to display this to the user as a transaction time but it doesn't look proper.
I would like to arrange it to be like 09/04/2013 16:37:05 or 09-apr-2013 16:37:05.
How do I go about and change the orders of the string?
As for now I could think is to use substr to separate the date and time. I'm still not sure on how to add the additional characters and rearrange the date.
why not use date() just like below,try this
$t = strtotime('20130409163705');
echo date('d/m/y H:i:s',$t);
and will be output
09/04/13 16:37:05
For PHP 5 >= 5.3.0 http://www.php.net/manual/en/datetime.createfromformat.php
$datetime = "20130409163705";
$d = DateTime::createFromFormat("YmdHis", $datetime);
echo $d->format("d/m/Y H:i:s"); // or any you want
Result:
09/04/2013 16:37:05
date("Y-m-d H:i:s", strtotime("2019-05-13"))
If you want to use substr(), you can easily add the dashes or slashes like this..
$datetime = "20130409163705";
$yyyy = substr($datetime,0,4);
$mm = substr($datetime,4,6);
$dd = substr($datetime,6,8);
$hh = substr($datetime,8,10);
$MM = substr($datetime,10,12);
$ss = substr($datetime,12,14);
$dt_formatted = $mm."/".$dd."/".$yyyy." ".$hh.":".$MM.":".$ss;
You can figure out any further formatting from that point.
You have different options.
Using date():
$format = date('d/m/y H:i:s', 1621371929);
echo $format;
the output is:
18/05/21 14:05:29
Using date_format():
$date = date_create(1621371929);
echo date_format($date, 'd/m/y H:i:s');
the output is:
18/05/21 14:05:29
Using DateTime::format():
$date = new DateTime('2021-05-18 14:05:29');
echo $date->format('d/m/y H:i:s');
the output is:
18/05/21 14:05:29
This article gives you an overview of these three methods, and this one is DateTime::format() in depth.
try this
$datetime = "20130409163705";
print_r(date_parse_from_format("Y-m-d H-i-s", $datetime));
the output:
[year] => 2013
[month] => 4
[day] => 9
[hour] => 16
[minute] => 37
[second] => 5
You could do it like this:
<?php
$datetime = "20130409163705";
$format = "YmdHis";
$date = date_parse_from_format ($format, $datetime);
print_r ($date);
?>
You can look at date_parse_from_format() and the accepted format values.
https://en.functions-online.com/date.html?command={"format":"l jS \\of F Y h:i:s A"}
You can use date_parse_from_format() function ...
date_parse_from_format(string $format, string $datetime): array
Example
<?php
$date = "6.1.2009 13:00+01:00";
print_r(date_parse_from_format("j.n.Y H:iP", $date));
?>
The above example will output:
Array
(
[year] => 2009
[month] => 1
[day] => 6
[hour] => 13
[minute] => 0
[second] => 0
[fraction] =>
[warning_count] => 0
[warnings] => Array
(
)
[error_count] => 0
[errors] => Array
(
)
[is_localtime] => 1
[zone_type] => 1
[zone] => 3600
[is_dst] =>
)
Check the PHP docs..you will get clear idea

Categories