Saniyeyi Saat: Dakika: Saniye Çevirme


330

Saniyeyi "Saat: Dakika: Saniye" biçimine dönüştürmem gerekiyor.

Örneğin: "685", "00:11:25" biçimine dönüştürüldü

Bunu nasıl başarabilirim?


4
soru belirsiz: Eğer dönüştürmek istediğiniz secondsbir etmek date/timeDakika: Saniye veya Saat bir miktara?
WonderLand

Yanıtlar:


741

gmdate()İşlevi kullanabilirsiniz :

echo gmdate("H:i:s", 685);

166
Yine de saniye sayısının 86.400'ün altında olduğundan emin olun.
Salathe

12
H, tek bir günde saat miktarını temsil eder. 90000 saniyeniz varsa ve üzerinde H kullanırsanız sonuç 01 olur (ertesi günün ilk saati). NOT 25 - günde sadece 24 saat vardır.
MarcinWolny

7
Bunun doğru yanıt olduğundan emin değilim, bu bir datetime... Ayrıca bazı olumsuz sonuçlara ihtiyacımız olursa (örneğin ofset ile çalışmak) işe yaramaz. -1toygar için
WonderLand

54
Bu, 24 saatten uzun sürelerdeki bariz kusur nedeniyle kabul edilen cevap olmamalıdır.
Scott Flack

10
Sayıların 85399'dan büyük olabileceği günlerde kullanmak için z'yi echo gmdate("z H:i:s", 685);0'dan başlayarak yılın gün sayısıdır. Özel ihtiyaçlarınızı karşılamak için php tarih kılavuzunu inceleyebilirsiniz.
Nightwolf

177

Bir saat 3600 saniyedir, bir dakika 60 saniyedir, neden olmasın:

<?php

$init = 685;
$hours = floor($init / 3600);
$minutes = floor(($init / 60) % 60);
$seconds = $init % 60;

echo "$hours:$minutes:$seconds";

?>

hangi üretir:

$ php file.php
0:11:25

(Bu kadar test etmedim, bu yüzden zeminle ilgili hatalar olabilir)


Ama o iki sıfır istiyor ... "00:11:25" değil "0:11:25"
animuson

52
printf("%02d:%02d:%02d", $hours, $minutes, $seconds);
Amber

5
İyi yanıt, ancak her işlem arasında $ init'ten $ hours * 3600 ve $ minutes * 60 çıkardığınızdan emin olun, aksi takdirde çift sayım dakika ve saniye alırsınız.
Mike Stowe

5
@ Amber'in yorumuna eklemek için sprintf, değeri yazdırmak yerine döndürmek için tuşlarını kullanın.
Allen Butler

77

Hadi bakalım

function format_time($t,$f=':') // t = seconds, f = separator 
{
  return sprintf("%02d%s%02d%s%02d", floor($t/3600), $f, ($t/60)%60, $f, $t%60);
}

echo format_time(685); // 00:11:25

1
Negatif değerler için çalışmaz. Negatif saniye aralığınız varsa, bunu kullanın:return ($t< 0 ? '-' : '') . sprintf("%02d%s%02d%s%02d", floor(abs($t)/3600), $f, (abs($t)/60)%60, $f, abs($t)%60); }
Ajax

66

Fonksiyonu gmdate() yalnızca saniyeler 86400(1 gün) altındaysa kullanın :

$seconds = 8525;
echo gmdate('H:i:s', $seconds);
# 02:22:05

Bkz. Gmdate ()

Demoyu Çalıştırın


Saniyeyi 'foot' limitsiz * formatına dönüştürün :

$seconds = 8525;
$H = floor($seconds / 3600);
$i = ($seconds / 60) % 60;
$s = $seconds % 60;
echo sprintf("%02d:%02d:%02d", $H, $i, $s);
# 02:22:05

Bakınız: floor () , sprintf () , aritmetik işleçler

Demoyu Çalıştırın


DateTimeUzantı kullanımı örneği :

$seconds = 8525;
$zero    = new DateTime("@0");
$offset  = new DateTime("@$seconds");
$diff    = $zero->diff($offset);
echo sprintf("%02d:%02d:%02d", $diff->days * 24 + $diff->h, $diff->i, $diff->s);
# 02:22:05

Bkz. DateTime :: __ construct () , DateTime :: modify () , klon , sprintf ()

Demoyu Çalıştırın


MySQL Örnek sonucun mertebesi saat veri türü, bu şekilde yerleştirilmiştir -838:59:59için838:59:59 :

SELECT SEC_TO_TIME(8525);
# 02:22:05

Bakınız: SEC_TO_TIME

Demoyu Çalıştırın


PostgreSQL örneği:

SELECT TO_CHAR('8525 second'::interval, 'HH24:MI:SS');
# 02:22:05

Demoyu Çalıştırın


30

Diğer çözümler kullanılır gmdate, ancak 86400 saniyeden uzun süren kenar durumlarda başarısız olur. Bunun üstesinden gelmek için saat sayısını kendimiz gmdatehesaplayabilir , ardından kalan saniyeleri dakika / saniye olarak hesaplayabiliriz.

echo floor($seconds / 3600) . gmdate(":i:s", $seconds % 3600);

Giriş: 6030 Çıkış:1:40:30

Giriş: 2000006030 Çıkış:555557:13:50


16
// TEST
// 1 Day 6 Hours 50 Minutes 31 Seconds ~ 111031 seconds

$time = 111031; // time duration in seconds

$days = floor($time / (60 * 60 * 24));
$time -= $days * (60 * 60 * 24);

$hours = floor($time / (60 * 60));
$time -= $hours * (60 * 60);

$minutes = floor($time / 60);
$time -= $minutes * 60;

$seconds = floor($time);
$time -= $seconds;

echo "{$days}d {$hours}h {$minutes}m {$seconds}s"; // 1d 6h 50m 31s

$ HMS = gmdate ( "H: i: s", 12720); Day-Hour-Min-Sec
mughal

7
gmdate("H:i:s", no_of_seconds);

1 günden büyükse (günde saniye) H:i:sformatta zaman vermeyecektir no_of_seconds.
Gün değerini ihmal eder ve sadeceHour:Min:Seconds

Örneğin:

gmdate("H:i:s", 89922); // returns 0:58:42 not (1 Day 0:58:42) or 24:58:42

6

İşte negatif saniyeleri ve 1 günden fazla saniyeyi işleyen bir astar.

sprintf("%s:%'02s:%'02s\n", intval($seconds/60/60), abs(intval(($seconds%3600) / 60)), abs($seconds%60));

Örneğin:

$seconds= -24*60*60 - 2*60*60 - 3*60 - 4; // minus 1 day 2 hours 3 minutes 4 seconds
echo sprintf("%s:%'02s:%'02s\n", intval($seconds/60/60), abs(intval(($seconds%3600) / 60)), abs($seconds%60));

çıkışlar: -26: 03: 04


negatif ve 1 saatten az ise çalışmaz: -3000 = 0:50:00 -0: 50: 00 olmalıdır
Tony Brix

6

Kabul edilen cevabı veya popüler cevapları sevmiyorsanız, bunu deneyin

function secondsToTime($seconds_time)
{
    if ($seconds_time < 24 * 60 * 60) {
        return gmdate('H:i:s', $seconds_time);
    } else {
        $hours = floor($seconds_time / 3600);
        $minutes = floor(($seconds_time - $hours * 3600) / 60);
        $seconds = floor($seconds_time - ($hours * 3600) - ($minutes * 60));
        return "$hours:$minutes:$seconds";
    }
}

secondsToTime(108620); // 30:10:20

5

bir dizi döndürmek için böyle yazma işlevi

function secondsToTime($seconds) {

  // extract hours
  $hours = floor($seconds / (60 * 60));

  // extract minutes
  $divisor_for_minutes = $seconds % (60 * 60);
  $minutes = floor($divisor_for_minutes / 60);

  // extract the remaining seconds
  $divisor_for_seconds = $divisor_for_minutes % 60;
  $seconds = ceil($divisor_for_seconds);

  // return the final array
  $obj = array(
      "h" => (int) $hours,
      "m" => (int) $minutes,
      "s" => (int) $seconds,
   );

  return $obj;
}

o zaman fonksiyonu şu şekilde çağırın:

secondsToTime(100);

çıktı

Array ( [h] => 0 [m] => 1 [s] => 40 )

4

Görmek:

    /** 
     * Convert number of seconds into hours, minutes and seconds 
     * and return an array containing those values 
     * 
     * @param integer $inputSeconds Number of seconds to parse 
     * @return array 
     */ 

    function secondsToTime($inputSeconds) {

        $secondsInAMinute = 60;
        $secondsInAnHour  = 60 * $secondsInAMinute;
        $secondsInADay    = 24 * $secondsInAnHour;

        // extract days
        $days = floor($inputSeconds / $secondsInADay);

        // extract hours
        $hourSeconds = $inputSeconds % $secondsInADay;
        $hours = floor($hourSeconds / $secondsInAnHour);

        // extract minutes
        $minuteSeconds = $hourSeconds % $secondsInAnHour;
        $minutes = floor($minuteSeconds / $secondsInAMinute);

        // extract the remaining seconds
        $remainingSeconds = $minuteSeconds % $secondsInAMinute;
        $seconds = ceil($remainingSeconds);

        // return the final array
        $obj = array(
            'd' => (int) $days,
            'h' => (int) $hours,
            'm' => (int) $minutes,
            's' => (int) $seconds,
        );
        return $obj;
    }

Kimden: Saniyeleri gün, saat, dakika ve saniyeye dönüştürün


3

Bunu dene:

date("H:i:s",-57600 + 685);

Alındığı
http://bytes.com/topic/php/answers/3917-seconds-converted-hh-mm-ss


Tamamen emin değilim, ancak zamanı 0'a ayarladığından eminim ve bunun üzerine her şey doğru cevap olacaktır
Kerry Jones

Bu, 0 ile önde gelen dakikaların önüne geçer, böylece tarihle ayarlayamazsınız () - ca.php.net/manual/en/function.date.php
barfoon

@barfoon - doğru, ama M.Ezz'in istediği şey bu ve zaman içinde kullanılan bir standart. Bu, "03:07:05" yerine "3: 7: 5", hatta "3: 7" yerine, benim için bir oran gibi görünüyor.
Kerry Jones

3

Bir projede çalıştığım saatleri izlediğim için gmtdate () işlevi benim için çalışmadı ve 24 saatten fazlaysa, 24 saat çıkarıldıktan sonra kalan tutarı alırsınız. Başka bir deyişle 37 saat 13 saat olur. (hepsi Glaviç tarafından belirtildiği gibi - örnekleriniz için teşekkürler!) Bu iyi çalıştı:

Convert seconds to format by 'foot' no limit :
$seconds = 8525;
$H = floor($seconds / 3600);
$i = ($seconds / 60) % 60;
$s = $seconds % 60;
echo sprintf("%02d:%02d:%02d", $H, $i, $s);
# 02:22:05

3

Bu işlev benim kullanışlı olabilir, genişletebilirsiniz:

function formatSeconds($seconds) {

if(!is_integer($seconds)) {
    return FALSE;
}

$fmt = "";

$days = floor($seconds / 86400);
if($days) {
    $fmt .= $days."D ";
    $seconds %= 86400;
}

$hours = floor($seconds / 3600);
if($hours) {
    $fmt .= str_pad($hours, 2, '0', STR_PAD_LEFT).":";
    $seconds %= 3600;
}

$mins = floor($seconds / 60 );
if($mins) {
    $fmt .= str_pad($mins, 2, '0', STR_PAD_LEFT).":";
    $seconds %= 60;
}

$fmt .= str_pad($seconds, 2, '0', STR_PAD_LEFT);

return $fmt;}

2

Çözüm: https://gist.github.com/SteveJobzniak/c91a8e2426bac5cb9b0cbc1bdbc45e4b

İşte çok temiz ve kısa bir yöntem!

Bu kod, sıkıcı işlev çağrıları ve parça parça dize oluşturma ve insanların bunun için yaptığı büyük ve hantal işlevlerden mümkün olduğunca kaçınır.

"1h05m00s" biçimini üretir ve sıfırdan farklı bir zaman bileşeninden önce geldiği sürece dakikalar ve saniyeler için önde gelen sıfırları kullanır.

Ve "0h00m01s" gibi işe yaramaz bilgiler vermekten kaçınmak için tüm boş önde gelen bileşenleri atlar (bunun yerine "1'ler" olarak görünür).

Örnek sonuçlar: "1s", "1m00s", "19m08s", "1h00m00s", "4h08m39s".

$duration = 1; // values 0 and higher are supported!
$converted = [
    'hours' => floor( $duration / 3600 ),
    'minutes' => floor( ( $duration / 60 ) % 60 ),
    'seconds' => ( $duration % 60 )
];
$result = ltrim( sprintf( '%02dh%02dm%02ds', $converted['hours'], $converted['minutes'], $converted['seconds'] ), '0hm' );
if( $result == 's' ) { $result = '0s'; }

Kodu daha da kısa (ancak daha az okunabilir) hale getirmek istiyorsanız, $converteddiziden kaçınabilirsiniz ve bunun yerine değerleri aşağıdaki şekilde doğrudan sprintf () çağrısına koyabilirsiniz:

$duration = 1; // values 0 and higher are supported!
$result = ltrim( sprintf( '%02dh%02dm%02ds', floor( $duration / 3600 ), floor( ( $duration / 60 ) % 60 ), ( $duration % 60 ) ), '0hm' );
if( $result == 's' ) { $result = '0s'; }

Yukarıdaki kod parçalarının her ikisinde de süre 0 veya daha yüksek olmalıdır . Negatif süreler desteklenmez. Ancak bunun yerine aşağıdaki alternatif kodu kullanarak negatif süreleri işleyebilirsiniz:

$duration = -493; // negative values are supported!
$wasNegative = FALSE;
if( $duration < 0 ) { $wasNegative = TRUE; $duration = abs( $duration ); }
$converted = [
    'hours' => floor( $duration / 3600 ),
    'minutes' => floor( ( $duration / 60 ) % 60 ),
    'seconds' => ( $duration % 60 )
];
$result = ltrim( sprintf( '%02dh%02dm%02ds', $converted['hours'], $converted['minutes'], $converted['seconds'] ), '0hm' );
if( $result == 's' ) { $result = '0s'; }
if( $wasNegative ) { $result = "-{$result}"; }
// $result is now "-8m13s"

O Not gmdate()kesmek sadece bundan daha kısadır, ancak 24 saate süreleri destekler. Eğer gmdate hile kullanırsanız 24 saatin üzerindeki herhangi bir şey başarısız olacaktır!
gw0

1

Bunun için DateTime'ı kullanmanın basit bir yolu:

    $time = 60; //sec.
    $now = time();
    $rep = new DateTime('@'.$now);
    $diff = new DateTime('@'.($now+$time));
    $return = $diff->diff($rep)->format($format);

    //output:  01:04:65

DateTime yöntemini kullanabilmenizi sağlayan basit bir çözümdür.


1

Java'da bu şekilde kullanabilirsiniz.

   private String getHmaa(long seconds) {
    String string;
    int hours = (int) seconds / 3600;
    int remainder = (int) seconds - hours * 3600;
    int mins = remainder / 60;
    //remainder = remainder - mins * 60;
    //int secs = remainder;

    if (hours < 12 && hours > 0) {
        if (mins < 10) {
            string = String.valueOf((hours < 10 ? "0" + hours : hours) + ":" + (mins > 0 ? "0" + mins : "0") + " AM");
        } else {
            string = String.valueOf((hours < 10 ? "0" + hours : hours) + ":" + (mins > 0 ? mins : "0") + " AM");
        }
    } else if (hours >= 12) {
        if (mins < 10) {
            string = String.valueOf(((hours - 12) < 10 ? "0" + (hours - 12) : ((hours - 12) == 12 ? "0" : (hours - 12))) + ":" + (mins > 0 ? "0" + mins : "0") + ((hours - 12) == 12 ? " AM" : " PM"));
        } else {
            string = String.valueOf(((hours - 12) < 10 ? "0" + (hours - 12) : ((hours - 12) == 12 ? "0" : (hours - 12))) + ":" + (mins > 0 ? mins : "0") + ((hours - 12) == 12 ? " AM" : " PM"));
        }
    } else {
        if (mins < 10) {
            string = String.valueOf("0" + ":" + (mins > 0 ? "0" + mins : "0") + " AM");
        } else {
            string = String.valueOf("0" + ":" + (mins > 0 ? mins : "0") + " AM");
        }
    }
    return string;
}

0
function timeToSecond($time){
    $time_parts=explode(":",$time);
    $seconds= ($time_parts[0]*86400) + ($time_parts[1]*3600) + ($time_parts[2]*60) + $time_parts[3] ; 
    return $seconds;
}

function secondToTime($time){
    $seconds  = $time % 60;
    $seconds<10 ? "0".$seconds : $seconds;
    if($seconds<10) {
        $seconds="0".$seconds;
    }
    $time     = ($time - $seconds) / 60;
    $minutes  = $time % 60;
    if($minutes<10) {
        $minutes="0".$minutes;
    }
    $time     = ($time - $minutes) / 60;
    $hours    = $time % 24;
    if($hours<10) {
        $hours="0".$hours;
    }
    $days     = ($time - $hours) / 24;
    if($days<10) {
        $days="0".$days;
    }

    $time_arr = array($days,$hours,$minutes,$seconds);
    return implode(":",$time_arr);
}

0

Saniyeyi dakikalara, dakikalara ve saniyelere indirecek, ancak 24 saati aşacak ve günlere daha da düşmeyecek bir şeye ihtiyacım vardı.

İşte çalışan basit bir işlev. Muhtemelen geliştirebilirsiniz ... Ama işte burada:

function formatSeconds($seconds)
{
    $hours = 0;$minutes = 0;
    while($seconds >= 60){$seconds -= 60;$minutes++;}
    while($minutes >= 60){$minutes -=60;$hours++;}
    $hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
    $minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
    $seconds = str_pad($seconds, 2, '0', STR_PAD_LEFT);
    return $hours.":".$minutes.":".$seconds;
}

0
$given = 685;

 /*
 * In case $given == 86400, gmdate( "H" ) will convert it into '00' i.e. midnight.
 * We would need to take this into consideration, and so we will first
 * check the ratio of the seconds i.e. $given:$number_of_sec_in_a_day
 * and then after multiplying it by the number of hours in a day (24), we
 * will just use "floor" to get the number of hours as the rest would
 * be the minutes and seconds anyways.
 *
 * We can also have minutes and seconds combined in one variable,
 * e.g. $min_sec = gmdate( "i:s", $given );
 * But for versatility sake, I have taken them separately.
 */

$hours = ( $given > 86399 ) ? '0'.floor( ( $given / 86400 ) * 24 )-gmdate( "H", $given ) : gmdate("H", $given );

$min = gmdate( "i", $given );

$sec = gmdate( "s", $given );

echo $formatted_string = $hours.':'.$min.':'.$sec;

Bir işleve dönüştürmek için:

function getHoursFormat( $given ){

 $hours = ( $given > 86399 ) ? '0'.floor( ( $given / 86400 ) * 24 )-gmdate( "H", $given ) : gmdate("H", $given );

 $min = gmdate( "i", $given );

 $sec = gmdate( "s", $given );

 $formatted_string = $hours.':'.$min.':'.$sec;

 return $formatted_string;

}

0

Javascript bunu yapmak gerekirse, burada cevaplandığı gibi sadece bir kod satırında yapabilirsiniz JavaScript ile saniye HH-MM-SS dönüştürün . SECONDS ifadesini dönüştürmek istediğiniz öğeyle değiştirin .

var time = new Date(SECONDS * 1000).toISOString().substr(11, 8);

0

YouTube vb. Gibi bir ses / video süresi dizesi oluşturmak istiyorsanız şunları yapabilirsiniz:

($seconds >= 60) ? ltrim(gmdate("H:i:s", $seconds), ":0") : gmdate("0:s", $seconds)

Aşağıdaki gibi dizeleri döndürür:

55.55 => '0:55'
100   => '1:40'

Muhtemelen> 24 saat boyunca iyi çalışmaz.


0

Bunu yapmanın güzel bir yolu:

function time_converter($sec_time, $format='h:m:s'){
      $hour = intval($sec_time / 3600) >= 10 ? intval($sec_time / 3600) : '0'.intval($sec_time / 3600);
      $minute = intval(($sec_time % 3600) / 60) >= 10 ? intval(($sec_time % 3600) / 60) : '0'.intval(($sec_time % 3600) / 60);
      $sec = intval(($sec_time % 3600) % 60)  >= 10 ? intval(($sec_time % 3600) % 60) : '0'.intval(($sec_time % 3600) % 60);

      $format = str_replace('h', $hour, $format);
      $format = str_replace('m', $minute, $format);
      $format = str_replace('s', $sec, $format);

      return $format;
    }

-1

Herkesin bu güzel biçimlendirilmiş dönmek için basit bir işlev arıyor olması durumunda (OP istedi biçimi değil biliyorum), ben sadece bu ile geldim. Bunun temel aldığı kod için mughal'a teşekkürler.

function format_timer_result($time_in_seconds){
    $time_in_seconds = ceil($time_in_seconds);

    // Check for 0
    if ($time_in_seconds == 0){
        return 'Less than a second';
    }

    // Days
    $days = floor($time_in_seconds / (60 * 60 * 24));
    $time_in_seconds -= $days * (60 * 60 * 24);

    // Hours
    $hours = floor($time_in_seconds / (60 * 60));
    $time_in_seconds -= $hours * (60 * 60);

    // Minutes
    $minutes = floor($time_in_seconds / 60);
    $time_in_seconds -= $minutes * 60;

    // Seconds
    $seconds = floor($time_in_seconds);

    // Format for return
    $return = '';
    if ($days > 0){
        $return .= $days . ' day' . ($days == 1 ? '' : 's'). ' ';
    }
    if ($hours > 0){
        $return .= $hours . ' hour' . ($hours == 1 ? '' : 's') . ' ';
    }
    if ($minutes > 0){
        $return .= $minutes . ' minute' . ($minutes == 1 ? '' : 's') . ' ';
    }
    if ($seconds > 0){
        $return .= $seconds . ' second' . ($seconds == 1 ? '' : 's') . ' ';
    }
    $return = trim($return);

    return $return;
}

-1

Gelecekte bunu arayan herkes, bu ilk posterin istediği formatı verir.

$init = 685;
$hours = floor($init / 3600);
$hrlength=strlen($hours);
if ($hrlength==1) {$hrs="0".$hours;}
else {$hrs=$hours;} 

$minutes = floor(($init / 60) % 60);
$minlength=strlen($minutes);
if ($minlength==1) {$mins="0".$minutes;}
else {$mins=$minutes;} 

$seconds = $init % 60;
$seclength=strlen($seconds);
if ($seclength==1) {$secs="0".$seconds;}
else {$secs=$seconds;} 

echo "$hrs:$mins:$secs";

-3
<?php
$time=3*3600 + 30*60;


$year=floor($time/(365*24*60*60));
$time-=$year*(365*24*60*60);

$month=floor($time/(30*24*60*60));
$time-=$month*(30*24*60*60);

$day=floor($time/(24*60*60));
$time-=$day*(24*60*60);

$hour=floor($time/(60*60));
$time-=$hour*(60*60);

$minute=floor($time/(60));
$time-=$minute*(60);

$second=floor($time);
$time-=$second;
if($year>0){
    echo $year." year, ";
}
if($month>0){
    echo $month." month, ";
}
if($day>0){
    echo $day." day, ";
}
if($hour>0){
    echo $hour." hour, ";
}
if($minute>0){
    echo $minute." minute, ";
}
if($second>0){
    echo $second." second, ";
}
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.