Полезные функции обработки даты в PHP
Создание временных интервалов
<?php
/**
* Разделение временных интервалов по заданному времени начала и окончания и интервалу.
*
* @param int $interval
* @param string $start_time
* @param string $end_time
* @return array
*/
function getTimeSlot($interval, $start_time, $end_time)
{
$start = new DateTime($start_time);
$end = new DateTime($end_time);
$startTime = $start->format('H:i');
$endTime = $end->format('H:i');
$i=0;
$time = [];
while(strtotime($startTime) <= strtotime($endTime)){
$start = $startTime;
$end = date('H:i',strtotime('+'.$interval.' minutes',strtotime($startTime)));
$startTime = date('H:i',strtotime('+'.$interval.' minutes',strtotime($startTime)));
$i++;
if(strtotime($startTime) <= strtotime($endTime)){
$time[$i]['slot_start_time'] = $start;
$time[$i]['slot_end_time'] = $end;
}
}
return $time;
}
/**
* Ввременные интервалы с указанием даты и времени в PHP для текущей даты
*
* @param int $duration
* @param string $start
* @param string $end
* @return array
*/
function getTodaysTimeSlots($duration, $start, $end)
{
$time = array();
$start = new \DateTime($start);
$end = new \DateTime($end);
$start_time = $start->format('H:i');
$end_time = $end->format('H:i');
$currentTime = strtotime(Date('Y-m-d H:i'));
$i=0;
while(strtotime($start_time) <= strtotime($end_time)){
$start = $start_time;
$end = date('H:i',strtotime('+'.$duration.' minutes',strtotime($start_time)));
$start_time = date('H:i',strtotime('+'.$duration.' minutes',strtotime($start_time)));
$today = Date('Y-m-d');
$slotTime = strtotime($today.' '.$start);
if($slotTime > $currentTime){
if(strtotime($start_time) <= strtotime($end_time)){
$time[$i]['start'] = $start;
$time[$i]['end'] = $end;
}
$i++;
}
}
return $time;
}
// пример: создайте временные интервалы на 30 минут с 10:00 до 13:00.
$slots = getTimeSlot(30, '10:00', '13:00');
echo '<pre>';
print_r($slots);
// Выход
Array
(
[1] => Array
(
[slot_start_time] => 10:00
[slot_end_time] => 10:30
)
[2] => Array
(
[slot_start_time] => 10:30
[slot_end_time] => 11:00
)
[3] => Array
(
[slot_start_time] => 11:00
[slot_end_time] => 11:30
)
[4] => Array
(
[slot_start_time] => 11:30
[slot_end_time] => 12:00
)
[5] => Array
(
[slot_start_time] => 12:00
[slot_end_time] => 12:30
)
[6] => Array
(
[slot_start_time] => 12:30
[slot_end_time] => 13:00
)
)
?>
PHP
Преобразование даты и времени из одного часового пояса в другой
<?php
/**
* Convert a datetime from one timezone to another
*
* @param mixed $time
* @param mixed $from_tz
* @param mixed $to_tz
*
* @return string
*/
function convert_timezone($time, $from_tz, $to_tz) {
$from_tz = new DateTimeZone($from_tz);
$to_tz = new DateTimeZone($to_tz);
$date = new DateTime($time, $from_tz);
$date->setTimezone($to_tz);
return $date->format('Y-m-d H:i:s');
}
//convert_timezone('2016-01-01 00:00:00', 'UTC', 'Asia/Tokyo');
$converted_datetime = convert_timezone('09/12/2021 13:56', 'UTC', 'Asia/Dhaka');
echo $converted_datetime."\n";
$converted_datetime = convert_timezone('09/12/2021 13:56', 'EST', 'Asia/Dhaka');
echo $converted_datetime;
/*
output:
2021-09-12 19:56:00
2021-09-13 00:56:00
*/
PHP
Добавить количество дней к дате
<?php
// Set timezone
date_default_timezone_set('Europe/London');
$today = date('d/m/Y');
// Add 3 days to a date (today)
$n = 3;
$new_date = date('d/m/Y', time() + ($n * 24 * 60 * 60));
echo $today;
echo "<br />";
echo $new_date;
?>
PHP
Как создать ежемесячный календарь с помощью PHP
<style type="text/css">
table {
border:1px solid #aaa;
border-collapse:collapse;
background-color:#fff;
font-family: Verdana;
font-size:12px;
}
th {
background-color:#777;
color:#fff;
height:32px;
}
td {
border:1px solid #ccc;
height:32px;
width:32px;
text-align:center;
}
td.red {
color:red;
}
td.bg-yellow {
background-color:#ffffe0;
}
td.bg-orange {
background-color:#ffa500;
}
td.bg-green {
background-color:#90ee90;
}
td.bg-white {
background-color:#fff;
}
td.bg-blue {
background-color:#add8e6;
}
a {
color: #333;
text-decoration:none;
}
</style>
<table border='0' >
<?php
// Get the current date
$date = getdate();
// Get the value of day, month, year
$mday = $date['mday'];
$mon = $date['mon'];
$wday = $date['wday'];
$month = $date['month'];
$year = $date['year'];
$dayCount = $wday;
$day = $mday;
while($day > 0) {
$days[$day--] = $dayCount--;
if($dayCount < 0)
$dayCount = 6;
}
$dayCount = $wday;
$day = $mday;
if(checkdate($mon,31,$year))
$lastDay = 31;
elseif(checkdate($mon,30,$year))
$lastDay = 30;
elseif(checkdate($mon,29,$year))
$lastDay = 29;
elseif(checkdate($mon,28,$year))
$lastDay = 28;
while($day <= $lastDay) {
$days[$day++] = $dayCount++;
if($dayCount > 6)
$dayCount = 0;
}
// Days to highlight
$day_to_highlight = array(8, 9, 10, 11, 12, 22,23,24,25,26);
echo("<tr>");
echo("<th colspan='7' align='center'>$month $year</th>");
echo("</tr>");
echo("<tr>");
echo("<td class='red bg-yellow'>Sun</td>");
echo("<td class='bg-yellow'>Mon</td>");
echo("<td class='bg-yellow'>Tue</td>");
echo("<td class='bg-yellow'>Wed</td>");
echo("<td class='bg-yellow'>Thu</td>");
echo("<td class='bg-yellow'>Fri</td>");
echo("<td class='bg-yellow'>Sat</td>");
echo("</tr>");
$startDay = 0;
$d = $days[1];
echo("<tr>");
while($startDay < $d) {
echo("<td></td>");
$startDay++;
}
for ($d=1;$d<=$lastDay;$d++) {
if (in_array( $d, $day_to_highlight))
$bg = "bg-green";
else
$bg = "bg-white";
// Highlights the current day
if($d == $mday)
echo("<td class='bg-blue'><a href='#' title='Detail of day'>$d</a></td>");
else
echo("<td class='$bg'><a href='#' title='Detail of day'>$d</a></td>");
$startDay++;
if($startDay > 6 && $d < $lastDay){
$startDay = 0;
echo("</tr>");
echo("<tr>");
}
}
echo("</tr>");
?>
</table>
PHP
Вычисление разницы между датой рождения и текущим днем
<?php
// исходные даты
$bday = new DateTime('15.10.1976'); // day.month.year (or: year-month-day)
$now = new DateTime('00:00:00'); // current date-time
// объект с разницей между $now и $bday (y = year, m = month, d = day)
$diff = $now->diff($bday);
// Выход
echo sprintf('%d years, %d month, %d days', $diff->y, $diff->m, $diff->d);
// 37 years, 2 month, 4 days
?>
PHP
Расчет прошедшего времени
<?php
// Вариант 1
function time_elapsed_string($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = [
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
];
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}
echo time_elapsed_string('2017-05-05 00:22:35').PHP_EOL;
echo time_elapsed_string('@1493943755').PHP_EOL; # timestamp input
echo time_elapsed_string('2017-05-05 00:22:35', true).PHP_EOL;
?>
<?php
// Вариант 2
function time_elapsed_string($ptime){
$etime = time() - $ptime;
if ($etime < 1){
return '0 seconds';
}
$a = array( 365 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
$a_plural = array( 'year' => 'years',
'month' => 'months',
'day' => 'days',
'hour' => 'hours',
'minute' => 'minutes',
'second' => 'seconds'
);
foreach ($a as $secs => $str){
$d = $etime / $secs;
if ($d >= 1)
{
$r = round($d);
return $r . ' ' . ($r > 1 ? $a_plural[$str] : $str) . ' ago';
}
}
}
echo time_elapsed_string(1493943755);
?>
PHP
Расчетное время чтения в PHP
<?php
function readTime($content){
$words = str_word_count_utf8(strip_tags($content));
$minutes = floor($words / 200);
$seconds = floor($words % 200 / (200 / 60));
return $minutes . ' minute' . ($minutes == 1 ? '' : 's') . ', ' . $seconds . ' second' . ($seconds == 1 ? '' : 's');
}
function str_word_count_utf8($str) {
return count(preg_split('~[^\p{L}\p{N}\']+~u',$str));
}
$contetnt = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, quis gravida magna mi a libero. Fusce vulputate eleifend sapien. Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus. Nullam accumsan lorem in dui. Cras ultricies mi eu turpis hendrerit fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In ac dui quis mi consectetuer lacinia. Nam pretium turpis et arcu. Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum. Sed aliquam ultrices mauris. Integer ante arcu, accumsan a, consectetuer eget, posuere ut, mauris. Praesent adipiscing. Phasellus ullamcorper ipsum rutrum nunc. Nunc nonummy metus. Vestibulum volutpat pretium libero. Cras id dui. Aenean ut';
?>
<p>Estimated reading time: <?php echo readTime($contetnt); ?></p>
?>
PHP
Как рассчитать время выполнения в PHP
<?php
//place this before any script you want to calculate time
$time_start = microtime(true);
//do something
$time_end = microtime(true);
// calculate execution time
$execution_time = ($time_end - $time_start);
//execution time of the script
echo 'Total Execution Time: '.number_format((float) $execution_time, 10) .' seconds';
?>
PHP
Добавление дней к дате в PHP DateTime()
<?php
$oldDate = "2020-02-27";
$newDate = new DateTime($oldDate);
$newDate->add(new DateInterval('P1D')); // P1D means a period of 1 day
$fomattedDate = $date->format('Y-m-d');
echo $fomattedDate; //output: 2020-02-28
$oldDate = "2020-02-27";
$date1 = date("Y-m-d", strtotime($oldDate.'+ 1 days'));
$date2 = date("Y-m-d", strtotime($oldDate.'+ 2 days'));
echo $date1; //output: 2020-02-28
echo $date2; //output: 2020-02-29
PHP
Добавление дней к дате в PHP date_add()
<?php
$oldDate = date_create("2020-02-27");
date_add($oldDate, date_interval_create_from_date_string("1 day"));
echo date_format($date,"Y-m-d"); //output: 2020-02-28
?>
PHP
Получить текущий год в PHP
<?php
// Вариант 1
date($format, $timestamp);
$Date = date("d-m-Y");
echo "The current date is $Date.";
echo "\n";
$Year = date("Y");
echo "The current year is $Year.";
echo "\n";
$Year2 = date("y");
echo "The current year in two digits is $Year2.";
// Результат
// The current date is 20-04-2020.
// The current year is 2020.
// The current year in two digits is 20.
// Вариант 2
strftime($format, $timestamp);
$Date = strftime("%d-%m-%Y");
echo "The current date is $Date.";
echo "\n";
$Year = strftime("%Y");
echo "The current year is $Year.";
echo "\n";
$Year2 = strftime("%y");
echo "The current year in two digits is $Year2.";
// Результат
// The current date is 20-04-2020.
// The current year is 2020.
// The current year in two digits is 20.
// Вариант 3
$ObjectName = new DateTime();
$ObjectName->format($format);
$Object = new DateTime();
$Date = $Object->format("d-m-Y");
echo "The current date is $Date.";
echo "\n";
$Year = $Object->format("Y");
echo "The current year is $Year.";
echo "\n";
$Year2 = $Object->format("y");
echo "The current year in two digits is $Year2.";
// Результат
// The current date is 20-04-2020.
// The current year is 2020.
// The current year in two digits is 20.
PHP
Преобразование DateTime в строку в PHP - format()
<?php
$theDate = new DateTime('2020-03-08');
echo $stringDate = $theDate->format('Y-m-d H:i:s');
//output: 2020-03-08 00:00:00
?>
PHP
Преобразование DateTime в строку в PHP - date_format()
<?php
$date = date_create_from_format('d M, Y', '08 Mar, 2020');
echo $newFormat = date_format($date,"Y/m/d H:i:s");
//output: 2020/03/08 00:00:00
?>
PHP
Преобразование DateTime в строку в PHP - date_d.php
<?php
define ('DATE_ATOM', "Y-m-d\TH:i:sP");
define ('DATE_COOKIE', "l, d-M-y H:i:s T");
define ('DATE_ISO8601', "Y-m-d\TH:i:sO");
define ('DATE_RFC822', "D, d M y H:i:s O");
define ('DATE_RFC850', "l, d-M-y H:i:s T");
define ('DATE_RFC1036', "D, d M y H:i:s O");
define ('DATE_RFC1123', "D, d M Y H:i:s O");
define ('DATE_RFC2822', "D, d M Y H:i:s O");
define ('DATE_RFC3339', "Y-m-d\TH:i:sP");
define ('DATE_RSS', "D, d M Y H:i:s O");
define ('DATE_W3C', "Y-m-d\TH:i:sP");
$dateFormat = new DateTime(); // this will return current date
echo $stringDate = $date->format(DATE_ATOM);
//output: 2020-03-08T12:54:56+01:00
?>
PHP
Преобразование DateTime в строку в PHP - list()
<?php
$date = explode("/",date('d/m/Y/h/i/s')
list($day,$month,$year,$hour,$min,$sec) = $date);
echo $month.'/'.$day.'/'.$year.' '.$hour.':'.$min.':'.$sec;
//output: 03/08/2020 02:01:06
?>
PHP
Дата и время
ПрограммированиеPHPDate