Reputation: 48818
I have some dates stored in YYYY-MM-DD
format in a MySQL database that I need to pass to JQuery for use in a JQuery UI Calendar. The problem I'm having is that `2014-01-12
in PHP is January 12 2014, but February 12, 2014 in Javascript.
This is because 0 = January in Javascript.
So how can I reliably pass a date to Javascript?
I've tried doing a simple strtotime
"-month", but obviously that's not actually what I want -- I don't want exactly a month to be removed, I want the date to remain the same, but in a different format.
Thanks!
Update:
<script>
$(document).ready(function() {
<?php
$startDate = date("Y,n,j", strtotime('-1 month'));
$endDate = date("Y,n,j", strtotime('+1 year -1 month'));
?>
var startDate = new Date(<?php echo $startDate; ?>);
var endDate = new Date(<?php echo $endDate; ?>);
Upvotes: 1
Views: 142
Reputation: 12295
Something like this, should do the job:
Database query:
SELECT UNIX_TIMESTAMP(date_field) AS mydate FROM table;
In Javascript:
var jsDate = new Date(<?php echo mydate; ?> * 1000);
Upvotes: 1
Reputation: 324790
In JavaScript, months are zero-based. It might be nonsense at first, but consider this:
var names = ["Jan","Feb","Mar"...];
var thisMonth = names[date.getMonth()];
Pretty cool! But yeah, it's a gotcha, and subtracting a month in PHP won't fix it (especially if you're working in January).
You will need to subtract one from the months in the JavaScript side. Try this:
alert(new Date(<?php echo date("Y,n-1,j"); ?>));
Upvotes: 2