PHP timestamp date to user timezone

前端 未结 1 1675
耶瑟儿~
耶瑟儿~ 2020-12-15 12:31

I\'m pulling the raw generated mysql timestamp info of $item_date from the database as php date format:

if (($timestamp = strtotime($item_date)) === false) {         


        
相关标签:
1条回答
  • 2020-12-15 12:53

    This post has been updated to include a full-fledged example

    <?php
        session_start();
    
        if (isset($_POST['timezone']))
        {
            $_SESSION['tz'] = $_POST['timezone'];
            exit;
        }
    
        if (isset($_SESSION['tz']))
        {
            //at this point, you have the users timezone in your session
            $item_date = 1371278212;
    
            $dt = new DateTime();
            $dt->setTimestamp($item_date);
    
            //just for the fun: what would it be in UTC?
            $dt->setTimezone(new DateTimeZone("UTC"));
            $would_be = $dt->format('Y-m-d H:i:sP');
    
            $dt->setTimezone(new DateTimeZone($_SESSION['tz']));
            $is = $dt->format('Y-m-d H:i:sP');
    
            echo "Timestamp " . $item_date . " is date " . $is . 
                 " in users timezone " . $dt->getTimezone()->getName() .
                 " and would be " . $would_be . " in UTC<br />";
        }
    ?>
    
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.min.js"></script>
    <script language="javascript">
      $(document).ready(function() {
            <?php if (!isset($_SESSION['tz'])) { ?>
                $.ajax({
                    type: "POST",
                    url: "tz.php",
                    data: 'timezone=' + jstz.determine().name(),
                    success: function(data){
                        location.reload();
                    }
                });
    
            <?php } ?>        
        });
    </script>
    

    I hope this is now clear enough ;).

    0 讨论(0)
提交回复
热议问题