PHP에서 시간 차이를 분 단위로 가져오는 방법
PHP에서 두 날짜 사이의 미세한 차이를 계산하는 방법은 무엇입니까?
위의 답변은 이전 버전의 PHP에 대한 것입니다.PHP 5.3이 표준이므로 날짜 계산을 수행하려면 Date Time 클래스를 사용하십시오.예.
$start_date = new DateTime('2007-09-01 04:10:58');
$since_start = $start_date->diff(new DateTime('2012-09-11 10:25:00'));
echo $since_start->days.' days total<br>';
echo $since_start->y.' years<br>';
echo $since_start->m.' months<br>';
echo $since_start->d.' days<br>';
echo $since_start->h.' hours<br>';
echo $since_start->i.' minutes<br>';
echo $since_start->s.' seconds<br>';
$since_start는 DateInterval 객체입니다.days 속성은 사용할 수 있습니다(DateTime 클래스의 diff 메서드를 사용하여 DateInterval 개체를 생성했기 때문입니다).
위의 코드는 다음과 같이 출력됩니다.
합계 1837일
5년
0개월
10일
6시간
14분
2초
합계 시간(분)을 취득하려면 , 다음의 순서에 따릅니다.
$minutes = $since_start->days * 24 * 60;
$minutes += $since_start->h * 60;
$minutes += $since_start->i;
echo $minutes.' minutes';
다음과 같이 출력됩니다.
2645654분
두 날짜 사이의 실제 시간(분)입니다.Date Time 클래스는 서머타임(타임존에 따라 다름)을 고려하지만 "이전 방식"에서는 고려되지 않습니다.날짜 및 시간에 대한 매뉴얼을 참조하십시오.http://www.php.net/manual/en/book.datetime.php
답은 다음과 같습니다.
$to_time = strtotime("2008-12-13 10:42:00");
$from_time = strtotime("2008-12-13 10:21:00");
echo round(abs($to_time - $from_time) / 60,2). " minute";
과거의 가장 큰 것을 미래의 가장 큰 것에서 빼고 60으로 나누어라.
횟수는 Unix 형식으로 이루어지기 때문에 이 횟수는 초수를 나타내는 큰 숫자일 뿐입니다.January 1, 1970, 00:00:00 GMT
<?php
$date1 = time();
sleep(2000);
$date2 = time();
$mins = ($date2 - $date1) / 60;
echo $mins;
?>
<?php
$start = strtotime('12:01:00');
$end = strtotime('13:16:00');
$mins = ($end - $start) / 60;
echo $mins;
?>
출력:
75
내 프로그램에서도 작동했고date_diff
, 확인할 수 있습니다.date_diff
여기에 매뉴얼이 있습니다.
$start = date_create('2015-01-26 12:01:00');
$end = date_create('2015-01-26 13:15:00');
$diff=date_diff($end,$start);
print_r($diff);
원하는 결과를 얻을 수 있습니다.
시간대를 바꿀 수 있습니다.
$start_date = new DateTime("2013-12-24 06:00:00",new DateTimeZone('Pacific/Nauru'));
$end_date = new DateTime("2013-12-24 06:45:00", new DateTimeZone('Pacific/Nauru'));
$interval = $start_date->diff($end_date);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo 'Diff. in minutes is: '.($hours * 60 + $minutes);
블로그 사이트(과거 날짜와 서버 날짜의 차이)를 위해 이 기능을 작성했습니다.다음과 같은 출력을 얻을 수 있습니다.
'49초 전', '20분 전', '21시간 전' 등등
전달된 날짜와 서버의 날짜를 구분해 주는 기능을 사용하고 있습니다.
<?php
//Code written by purpledesign.in Jan 2014
function dateDiff($date)
{
$mydate= date("Y-m-d H:i:s");
$theDiff="";
//echo $mydate;//2014-06-06 21:35:55
$datetime1 = date_create($date);
$datetime2 = date_create($mydate);
$interval = date_diff($datetime1, $datetime2);
//echo $interval->format('%s Seconds %i Minutes %h Hours %d days %m Months %y Year Ago')."<br>";
$min=$interval->format('%i');
$sec=$interval->format('%s');
$hour=$interval->format('%h');
$mon=$interval->format('%m');
$day=$interval->format('%d');
$year=$interval->format('%y');
if($interval->format('%i%h%d%m%y')=="00000") {
//echo $interval->format('%i%h%d%m%y')."<br>";
return $sec." Seconds";
} else if($interval->format('%h%d%m%y')=="0000"){
return $min." Minutes";
} else if($interval->format('%d%m%y')=="000"){
return $hour." Hours";
} else if($interval->format('%m%y')=="00"){
return $day." Days";
} else if($interval->format('%y')=="0"){
return $mon." Months";
} else{
return $year." Years";
}
}
?>
"date.php"라고 가정하여 파일로 저장합니다.이와 같이 다른 페이지에서 함수를 호출합니다.
<?php
require('date.php');
$mydate='2014-11-14 21:35:55';
echo "The Difference between the server's date and $mydate is:<br> ";
echo dateDiff($mydate);
?>
물론 함수를 수정하여 두 개의 값을 전달할 수 있습니다.
DateTime::diff
쿨하지만 단일 단위 결과를 필요로 하는 이런 종류의 계산에는 어색합니다.타임스탬프를 수동으로 감산하는 것이 효과적입니다.
$date1 = new DateTime('2020-09-01 01:00:00');
$date2 = new DateTime('2021-09-01 14:00:00');
$diff_mins = abs($date1->getTimestamp() - $date2->getTimestamp()) / 60;
이게 너에게 도움이 될 것 같아
function calculate_time_span($date){
$seconds = strtotime(date('Y-m-d H:i:s')) - strtotime($date);
$months = floor($seconds / (3600*24*30));
$day = floor($seconds / (3600*24));
$hours = floor($seconds / 3600);
$mins = floor(($seconds - ($hours*3600)) / 60);
$secs = floor($seconds % 60);
if($seconds < 60)
$time = $secs." seconds ago";
else if($seconds < 60*60 )
$time = $mins." min ago";
else if($seconds < 24*60*60)
$time = $hours." hours ago";
else if($seconds < 24*60*60)
$time = $day." day ago";
else
$time = $months." month ago";
return $time;
}
php > 5.2로 xx번 전에 이렇게 표시했습니다.Date Time 객체에 대한 자세한 내용은 다음과 같습니다.
//Usage:
$pubDate = $row['rssfeed']['pubDates']; // e.g. this could be like 'Sun, 10 Nov 2013 14:26:00 GMT'
$diff = ago($pubDate); // output: 23 hrs ago
// Return the value of time different in "xx times ago" format
function ago($timestamp)
{
$today = new DateTime(date('y-m-d h:i:s')); // [2]
//$thatDay = new DateTime('Sun, 10 Nov 2013 14:26:00 GMT');
$thatDay = new DateTime($timestamp);
$dt = $today->diff($thatDay);
if ($dt->y > 0){
$number = $dt->y;
$unit = "year";
} else if ($dt->m > 0) {
$number = $dt->m;
$unit = "month";
} else if ($dt->d > 0) {
$number = $dt->d;
$unit = "day";
} else if ($dt->h > 0) {
$number = $dt->h;
$unit = "hour";
} else if ($dt->i > 0) {
$number = $dt->i;
$unit = "minute";
} else if ($dt->s > 0) {
$number = $dt->s;
$unit = "second";
}
$unit .= $number > 1 ? "s" : "";
$ret = $number." ".$unit." "."ago";
return $ret;
}
function date_getFullTimeDifference( $start, $end )
{
$uts['start'] = strtotime( $start );
$uts['end'] = strtotime( $end );
if( $uts['start']!==-1 && $uts['end']!==-1 )
{
if( $uts['end'] >= $uts['start'] )
{
$diff = $uts['end'] - $uts['start'];
if( $years=intval((floor($diff/31104000))) )
$diff = $diff % 31104000;
if( $months=intval((floor($diff/2592000))) )
$diff = $diff % 2592000;
if( $days=intval((floor($diff/86400))) )
$diff = $diff % 86400;
if( $hours=intval((floor($diff/3600))) )
$diff = $diff % 3600;
if( $minutes=intval((floor($diff/60))) )
$diff = $diff % 60;
$diff = intval( $diff );
return( array('years'=>$years,'months'=>$months,'days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
}
else
{
echo "Ending date/time is earlier than the start date/time";
}
}
else
{
echo "Invalid date/time data detected";
}
}
반환되는 보다 보편적인 버전은 분수/소수를 포함하여 일, 시간, 분 또는 초 단위로 표시됩니다.
function DateDiffInterval($sDate1, $sDate2, $sUnit='H') {
//subtract $sDate2-$sDate1 and return the difference in $sUnit (Days,Hours,Minutes,Seconds)
$nInterval = strtotime($sDate2) - strtotime($sDate1);
if ($sUnit=='D') { // days
$nInterval = $nInterval/60/60/24;
} else if ($sUnit=='H') { // hours
$nInterval = $nInterval/60/60;
} else if ($sUnit=='M') { // minutes
$nInterval = $nInterval/60;
} else if ($sUnit=='S') { // seconds
}
return $nInterval;
} //DateDiffInterval
곱셈을 빼고 60으로 나누세요.
다음 예시는 다음 날짜로부터 경과시간을 계산하는 것입니다.2019/02/01 10:23:45
단위: 삭제:
$diff_time=(strtotime(date("Y/m/d H:i:s"))-strtotime("2019/02/01 10:23:45"))/60;
두 날짜의 차이를 찾는 나의 해결책은 여기에 있다.초, 분, 시간, 일, 년, 월 등의 차이를 찾을 수 있습니다.
function alihan_diff_dates($date = null, $diff = "minutes") {
$start_date = new DateTime($date);
$since_start = $start_date->diff(new DateTime( date('Y-m-d H:i:s') )); // date now
print_r($since_start);
switch ($diff) {
case 'seconds':
return $since_start->s;
break;
case 'minutes':
return $since_start->i;
break;
case 'hours':
return $since_start->h;
break;
case 'days':
return $since_start->d;
break;
default:
# code...
break;
}
}
이 기능을 개발할 수 있습니다.테스트도 하고, 일도 하고 있습니다.DateInterval 객체의 출력은 다음과 같습니다.
/*
DateInterval Object ( [y] => 0 [m] => 0 [d] => 0 [h] => 0 [i] => 5 [s] => 13 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 0 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
*/
기능 사용:
$date = 과거 날짜, $diff = "분", "일", "초"를 입력합니다.
$diff_mins = alihan_diff_dates("2019-03-24 13:24:19", "minutes");
행운을 빌어요.
$date1=date_create("2020-03-15");
$date2=date_create("2020-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
형식 지정자에 대한 자세한 내용은 링크를 참조하십시오.
차이를 분 단위로 계산하는 또 다른 간단한 방법입니다.이것은 1년 이내의 계산용 샘플입니다.자세한 내용은 여기를 클릭해 주세요.
$origin = new DateTime('2021-02-10 09:46:32');
$target = new DateTime('2021-02-11 09:46:32');
$interval = $origin->diff($target);
echo (($interval->format('%d')*24) + $interval->format('%h'))*60; //1440 (difference in minutes)
이게 도움이 될 거야...
function get_time($date,$nosuffix=''){
$datetime = new DateTime($date);
$interval = date_create('now')->diff( $datetime );
if(empty($nosuffix))$suffix = ( $interval->invert ? ' ago' : '' );
else $suffix='';
//return $interval->y;
if($interval->y >=1) {$count = date(VDATE, strtotime($date)); $text = '';}
elseif($interval->m >=1) {$count = date('M d', strtotime($date)); $text = '';}
elseif($interval->d >=1) {$count = $interval->d; $text = 'day';}
elseif($interval->h >=1) {$count = $interval->h; $text = 'hour';}
elseif($interval->i >=1) {$count = $interval->i; $text = 'minute';}
elseif($interval->s ==0) {$count = 'Just Now'; $text = '';}
else {$count = $interval->s; $text = 'second';}
if(empty($text)) return '<i class="fa fa-clock-o"></i> '.$count;
return '<i class="fa fa-clock-o"></i> '.$count.(($count ==1)?(" $text"):(" ${text}s")).' '.$suffix;
}
너무 많은 해결책을 찾았지만 정확한 해결책을 찾지 못했어요.하지만 회의록을 찾기 위해 코드를 만들었습니다. 확인하세요.
<?php
$time1 = "23:58";
$time2 = "01:00";
$time1 = explode(':',$time1);
$time2 = explode(':',$time2);
$hours1 = $time1[0];
$hours2 = $time2[0];
$mins1 = $time1[1];
$mins2 = $time2[1];
$hours = $hours2 - $hours1;
$mins = 0;
if($hours < 0)
{
$hours = 24 + $hours;
}
if($mins2 >= $mins1) {
$mins = $mins2 - $mins1;
}
else {
$mins = ($mins2 + 60) - $mins1;
$hours--;
}
if($mins < 9)
{
$mins = str_pad($mins, 2, '0', STR_PAD_LEFT);
}
if($hours < 9)
{
$hours =str_pad($hours, 2, '0', STR_PAD_LEFT);
}
echo $hours.':'.$mins;
?>
예를 들어 01시간 02분 01:02와 같이 시간과 분 단위로 출력을 제공합니다.
다음은 간단한 원라이너입니다.
$start = new DateTime('yesterday');
$end = new DateTime('now');
$diffInMinutes = iterator_count(new \DatePeriod($start, new \DateInterval('PT1M'), $end));
이거 먹어봐
$now = \Carbon\Carbon::now()->toDateString(); // get current time
$a = strtotime("2012-09-21 12:12:22");
$b = strtotime($now);
$minutes = ceil(($a - $b) / 3600); it will get ceiling value
언급URL : https://stackoverflow.com/questions/365191/how-to-get-time-difference-in-minutes-in-php
'source' 카테고리의 다른 글
Google Chrome에서 JavaScript 디버거를 시작하려면 어떻게 해야 합니까? (0) | 2022.10.13 |
---|---|
PHP를 사용하여 두 날짜의 차이를 계산하는 방법은 무엇입니까? (0) | 2022.10.13 |
MySQL은 하나의 열과 대응하는 다른 열을 선택합니다. (0) | 2022.10.13 |
System.out.println 출력 컬러링 방법 (0) | 2022.10.13 |
JavaScript에서 두 변수를 스왑하는 방법 (0) | 2022.10.13 |