简体   繁体   中英

How include script only on certain time

I want to include script only on certain time from 7:00AM US time and turn off at 1:00PM .

This is what I have:

date_default_timezone_set( 'America/New_York' );
$time = date( 'H' ); ?>
<script>console.log('<?php echo $time; ?>');</script>
<?php if($time >= 07 && $time <= 01) : ?>
    <script>alert("That works!");</script>
endif;

I understand that I'm trying to compare a larger number firstly, but don't understand what I need to do.

24-format doesn't work too.

Thanks!

Try this

<?php
date_default_timezone_set( 'America/New_York' );
$current_time = date('H:i a');
$US1 = "7:00AM";
$US2 = "1:00PM";
$date1 = DateTime::createFromFormat('H:i a', $current_time);
$date2 = DateTime::createFromFormat('H:i a', $US1);
$date3 = DateTime::createFromFormat('H:i a', $US2);
if ($date1 > $date2 && $date1 < $date3)
{
   echo '<script type="text/javascript" src="/js/livechat.js"></script>';
}
?>

当您在date()使用H时,将给出小时的24小时格式,因此您的测试可能应针对7和13。

<?php if($time >= 7 && $time <= 13) : ?>

You need to use the time without leading zero like so:

<?php
date_default_timezone_set('America/New_York');
$hour = (new DateTime())->format('G');
?>
<script>console.log('<?php echo $time; ?>');</script>
<?php if ($hour >= 7 && $hour <= 13): ?>
<script>alert("That works!");</script>
<?php endif; ?>

This can be accomplished with timestamp comparison:

date_default_timezone_set( 'America/New_York' );
if (strtotime(date('H:i')) >= strtotime('7:00') && 
    strtotime(date('H:i')) <= strtotime('13:00')) { /* do stuff */ }

To get 1pm you should use military time... it's 13 o'clock.

I recommend doing it this way instead of just comparing hours because if you wish to specify a different time in the future it is very flexible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM