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; ?>);
2 Answers 2
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"); ?>));
1 Comment
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);
4 Comments
date. I think I'd rather stay with that than introducing new date formats, thanks.
The problem I'm having is that 2014年01月12日 in PHP is January 12 2014, but February 12, 2014 in Javascript.-- Show us how you pass the dates.