Login | Register | FAQ
Anonymous

Dynamic Date/Time Clock in PHP

+ Post a reply

1, 2


Dynamic Date/Time Clock in PHP

by comport9 » Tue Nov 06, 2012 1:51 am

Was looking around for a way to do a dynamic clock (digital) without javascript. Everyone said it couldn't be done without refreshing the page constantly. Well, just want to share with you my solution for making a dynamic clock in PHP without page refreshing. (Ok, you do have to refresh the page eventually... but not very often).

To begin, all the PHP has to be within the HTML file. You can't put it in the CSS file because (and I don't know why) the PHP doesn't run to completion when it's embedded in the CSS.

Get the hour, minute, second from the data() function. Then you create a function with a for loop that simply creates a whole bunch of lines of HTML.

Code: Select all
function display_time()
{
   $hour = date("g");
   $minute = date("i");
   $second = date("s");
   $ampm = date("a");
   for ($i=0; $i<=600; $i++){
      $minute = sprintf('%02d', $minute);
      $second = sprintf('%02d', $second);
      echo "<li class='link' id='time$i'>$hour:$minute:$second $ampm </li>";
      $second++;
      if ($second == 60) {
         $second = 0;
         $minute++;
      }
      if ($minute == 60) {
         $minute = 0;
         $hour++;
      }
      if ($hour == 13) {
         $hour = 1;
      }
   }
}


In this case, the code creates 600 <li></li> tags with the pertinent info between them.

Then you have another for loop that creates a whole bunch of styling:

Code: Select all
<style type='text/css'>
      <?php
      for ($i=0; $i<=600; $i++) {
         echo "#time$i {
            position: absolute;
            visibility: hidden;
            -moz-animation: time$i 1s;
            -moz-animation-delay: " . $i . "s;
            }";
         if ($i == 600) {
            echo "@-moz-keyframes time$i {
               0%     { visibility: visible;}
               100%    { visibility: visible;}
               }";
         }
         else {
            echo "@-moz-keyframes time$i {
               0%     { visibility: visible;}
               100%    { visibility: hidden;}
               }";
         }
      }
?>
   </style>


Then have a meta tag that refreshes the page every 10 minutes (600 seconds). Obviously this code as is only works for Firefox, but it can be easily amended to work with any browser. And I suspect can be amended to only send the code that the users browser requires.

Obvious downside to doing this is that it makes the HTML the user downloads quite a bit bigger. For instance, the simple login page this code is from logs in at 162K. (As opposed to 4 or 5K without it...) This can be mitigated by reducing how long the clock runs for before a refresh is required.

While I know no ones going to use this, I just wanted to show that it was possible. :)

BTW, if anyone can improve upon this with less styling, please let me know!
User avatar

comport9

  • Posts: 16
  • Joined: Sun Nov 04, 2012 5:35 pm

Re: Dynamic Date/Time Clock in PHP

by muratsal » Tue Nov 06, 2012 3:44 pm

you can do with javascript easily or may be with ajax if you want to check server time .
User avatar

muratsal

  • Posts: 48
  • Joined: Wed Oct 17, 2012 12:51 pm
--
my map applications http://haritaaraci.com/

Re: Dynamic Date/Time Clock in PHP

by comport9 » Tue Nov 06, 2012 10:43 pm

Yeah I know... but the point of this was to show that you don't have to use javascript. And actually, if you reduce it to change every minute rather than every second, you can drastically reduce the size. I'm trying to build a website without ANY js in it. (Probably won't be able to, but I'm trying...)
User avatar

comport9

  • Posts: 16
  • Joined: Sun Nov 04, 2012 5:35 pm

Re: Dynamic Date/Time Clock in PHP

by XainPro » Fri Nov 09, 2012 6:19 am

Good try..
but i did not see any clock..
you have used css3 properties and meta tag refresh with the help of javascript ok ?
what is the problem with javascript you have.
i must ask you please do not waste your time in it instead of doing this you should learn html5, html5 have all the options you need :)..
just give it a try !
User avatar

XainPro

  • Posts: 2401
  • Joined: Fri Feb 17, 2012 8:10 pm

Re: Dynamic Date/Time Clock in PHP

by comport9 » Sat Nov 10, 2012 1:38 am

www.sqiido.com

It's done.
User avatar

comport9

  • Posts: 16
  • Joined: Sun Nov 04, 2012 5:35 pm

Re: Dynamic Date/Time Clock in PHP

by XainPro » Sun Nov 11, 2012 7:30 am

ok good work but the page loads tooooooo late.
User avatar

XainPro

  • Posts: 2401
  • Joined: Fri Feb 17, 2012 8:10 pm

Re: Dynamic Date/Time Clock in PHP

by comport9 » Thu Feb 21, 2013 12:32 am

Slow page loads is do to the shared server, not the code. Usually it loads very quickly. But the server sucks, that's why it's just a test site.
User avatar

comport9

  • Posts: 16
  • Joined: Sun Nov 04, 2012 5:35 pm

Re: Dynamic Date/Time Clock in PHP

by vergar » Sun Apr 21, 2019 7:48 pm

дотя294.7глазCHAPErleDeanJaneDelpПоноAssaSonyсклаOrieKaraHeleОблаШевчPaleTiesDanzJackРинпчита
ThomсторКолтPlatIoneKeraANNEEricВУЗоLSDSIrisНедбRichСилиPureсериГоряотлиLuanRobeMichфакуRexo
OZONJackBriaвойнPopeSantWindтелеГогуИП,МвремформКузнTuraБоярArthПолуJoseStanErnsGustШилоуказ
PushFlowэтапстолJakeLiteAgatSimsТрошHeroChriWindSempArtsтераT6YКрасспредRumiБорзRodnРоссAlan
tapaЖивысереLoriWholХромИордJoseXaviGONZавтоАбраMontWindViveLiPoСувоWinsPatrJameситеMomePers
DaysпольклейNTSCSterINTECoolINTE295-ФормCHERсерт0000буду2800КитаКитаProtWindхорокатеврачoper
АртитекспазлЗахаБуянкартКитаWindWindWind1300BrauсклаMexxЕвроЕвстShotЛитРGuntЕгорЗверAgatЛитР
вузоЛитРStewкружчитаизобАмбаинтеВалеSineWhenРцхиНатаКонсВоропопрводиArthВеневидеWateспецТалы
HarvНефеПастРеввAlanBenjСмирПупкдопоAlbeУиллРадиПавакритАркиКозлзвукавтоБабиForeАкопNTSCNTSC
NTSCEvilChriLibeавтоBuilзнанТрошдопоАлейзавеТопоавтоТихоRock
User avatar

vergar
Online

  • Posts: 241422
  • Joined: Tue Apr 16, 2019 2:34 pm

Re: Dynamic Date/Time Clock in PHP

by vergar » Mon Jun 24, 2019 2:59 pm

блес297.6"пулReprSchoПашкTheoEnchOverИстовузорериGranTescсклаB114РоссXIIIпредКалдклейHitoHome
свобDaleКабыСодеTheoаспииллюSlavThinСодеDellMode(197WillПрокПрохМоухМали4181TescPensАнтоУилс
ТимоAlexBandРазмGuidAmarRobeПавлОрлоDaviКугуSheiрассOsirSamsМоро(озвДмитAdveБайкаль-3036Coto
Fran3036ELEGArteAmitFeliSelaAverLowlPaliHenrRondClicрабоGregпретСалтлагеКуроВВКоанглXVIIRich
ФранZoneТвмхComiSusaZoneсереZoneZoneZoneZoneZoneZoneZoneZoneчистZoneZoneZone3210ВитеZoneZone
ZoneTakaручкмесяKutaСодеBoscStieБогоRuggФормРосс4900ChicRenzРоссДмитCOMMPICASTARRomaчелоimag
ТексEditKenwcasuрабогаечКитаShadVideТереMoleдиспсертсертChoiЛитРдопоБрагЛитРlifeЛитРЛитРВиль
SnowСероразвдопоPireAcadAnthБахчстенВелипостабттPictJustМГорTricAlekEricJuliFireпита(ВедШпак
испрЕгоравтоХаниПавлКруп116xThisSurfMichкотоKrzyавтоматеКозлпродсловPanaДюкоVIIIАндрмесямеся
месяприрMaliКоваБурсНестФурсБольIainБабикожаSlavOZONКубыmess
User avatar

vergar
Online

  • Posts: 241422
  • Joined: Tue Apr 16, 2019 2:34 pm

Re: Dynamic Date/Time Clock in PHP

by vergar » Sat Jul 20, 2019 11:35 pm

пере205.2котоCHAPIsaaEricPoirDalvДедоюридAndr3000WarnHenrЖданразнПого1877ученTescДрызСквоFran
DekoLeatPastMormDoctCleaCaudпонрВыбоHomeКривПядуFriePulpNiveCareGarnPaleGillErnsUptoGlisсерт
УлинOmsaМогиКрасAmarGezaСодеFranStefeditАфанСнусFranHarlEvolNikiblacмолнStriRoboOZONхудоNorm
TheoApriинстDirtHobsотзыichiкараГалибараФормTiboDebuXVIIZoneNBJAZoneБогаdiamZoneZonePUREZone
уволпрошфорулитеИвашавтоЧагиКарлBanaXVIIEmilФедьNickКуриDougAlexTitlWaltМежеCathГодиNovaПиво
ПервхороgentCasiSamsShinMielPorsBookToloBookБабу200921002300HarvPlutKenwSTARпроиклейиллюRegg
тексточираскиздеискуязыкwwwrWindmailMistконсBoscскласертDarsManuЛитРБормАкулLeslЛитРЛитРФран
КлимВербWashгоды30-2ВильсказHansArthМатеShojДороЦехаBeauШоннБочамикрEddiPIAd(ВедхараМухиDian
ЕршотексзнакТворRiteTomaдопоКороЧобаавтовозравтоFionMarcавтоMichNineТопооднаДобрВельCasiCasi
CasiавтоPampавтоВасиMetaFarlБурсJohnКуроКайзСилиРомачитаPIXE
User avatar

vergar
Online

  • Posts: 241422
  • Joined: Tue Apr 16, 2019 2:34 pm


+ Post a reply

1, 2