Working with dates in PHP and Javascript

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; ?>);

Answers


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"); ?>));

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);

Need Your Help

Assigning a 'for loop' to a variable in a python program

python mysql database input

Im writing a program at the moment that interacts with a MySQL database and im having a problem. As you can see I've written a query that will look for products in the products table that correspon...

Exception caught while running junit

java spring junit mockmvc

I am getting below error while checking the output of my junit, it seems there is something wrong with JSON path provided with spring.