Jack Maessen Jack Maessen - 2 months ago 16x
Javascript Question

how to convert strtotime in php to new Date in js

For a realtime countdown i use some php variables and echo them in the js like below:

$expire_year = '2016'; // year
$expire_month = '8'; // month ( 8 = August)
$expire_day = '14'; // day (14th)
$expire_hour = '2'; // hour ( 1-24)
$expire_minutes = '12'; // minutes

i use them in the js like blow:

timestamp = new Date(<?php echo $expire_year; ?>, <?php echo $expire_month - 1; ?>, <?php echo $expire_day; ?>, <?php echo $expire_hour; ?>, <?php echo $expire_minutes; ?>),

This works fine!

I use php
to check if the date really has expired:

$quickpollexpiredate = strtotime("August 14, 2016 2:12"); // set an expiration date

So for the countdown timer in js and for the check in php, i have to use 2 different date "structures".

Is it possible to make a check in php so that i have to use only the 5 variables ($expire_year, $expire_month...) with strtotime() or another function?

So actually what i want to achieve is something like this (ofcourse this is wrong, but i hope you understand what i am trying to achieve)

$quickpollexpiredate = strtotime($expire_year, $expire_month, $expire_day, $expire_hour, $expire_minutes); // set an expiration date


If you have a timestamp in php, you can easily use it to set a Date object in javascript. You just need to consider that a timestamp in javascript is in milliseconds and not seconds like in php:

jsTimestamp = new Date(<?php echo $phpTimestamp; ?> * 1000);


jsTimestamp = new Date(<?php echo strtotime($yourDateString); ?> * 1000);

Note that new Date(...) also accepts strings, see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date for more details.