Ok, Im trying to convert a javascript timestamp to a php equivalent, I have surfed the posts here on stack for a decent answer as well as various other sites so this question comes as a last ditch effort despite knowing Im likely to get down votes, and someone telling me nothing more than this is a dupe question from somewhere else. So despite that..
This is my failure of an attempt thus far. Please Note I am using jQuery, with noConflict hence the j rather than the $
var yr = j('#time_year :selected').val();//year
var mn = j('#time_month :selected').val();//month
var dy = j('#time_day :selected').val();//day
var hr = j('#time_hour :selected').val();//hour
var min = j('#time_minute :selected').val();//minute
var sc = j('#time_second :selected').val();//second
if(j('#time_ampm :selected').val() == 12 && j('#time_hour :selected').val() < 12){hr = j('#time_hour :selected').val()+12;}
if(j('#time_ampm :selected').val() == 0 && j('#time_hour :selected').val() == 12){hr = 0;}
var theDate = new Date(yr, mn, dy, hr, min, sc).getTime();
setTimeStamps(theDate);
j('#timestamp_now_js').html(" "+theTime);
j('#timestamp_now_php').html(" "+Math.round(theTime / 1000));
The select values at the top are based off of Mozilla.org Date reference using 0-nn as they describe. Where as the am/pm if-else is essentially meant to add 12 hours to the time selected as the time displayed on the site is 12-hour format. Javascript uses 24-hour. Its also there in the event that if am is picked and the use 12 it will convert 12 to 0 to match the 24-hour formatting concept.
Currently what appears to be happening is that despite it seeming to work, when I run the timestamp given through a php date() function it shows a date thats about a month 2 weeks and a few days a head of what I am testing off of, which is the equivalent of now
I would create a jsFiddle of the whole thing html included, but I use php through out to generate my select boxes. So with that if you want to see what I have “live” then go to http://7pz.net/timestamps.php as thats where I am testing the concept.
That’s because in Javascript’s
Dateobjects the month range is 0-11, not 1-12. That’s for the “month” part. Try this:Or better, generate the
<option>s with values ranging from 0 to 11.Plus, this statement:
Remember that
j('#time_hour :selected').val()is a string, not a number, so you have to convert it before adding 12, or else you’d get something like"0412". You’re creating a date with the hour count set to 412, i.e. 17 days and 4 hours. And 17 days are addes to the day count.Fix it like this:
I used the plus unary operator.
(P.S.: there’s a lot of room to improve your code, starting with readability and jQuery object caching. Take some time improving your Javascript coding skills before getting used to some bad practices.)