If your variable $dta_inicial
contains a string representing a date (eg.: 17/12/2015
) and you make a echo
of this variable, then its contents will be inserted as such in the output. That is, it:
preencheform_edicaoJS(...,<?php echo $dta_inicial; ?>)
You’ll end up generating this:
preencheform_edicaoJS(...,17/12/2015)
And since Javascript does not have a literal for dates, this will be interpreted as a numerical expression (such as pointed out by gustavox in the comments) and then evaluated (resulting in a number).
If you want Javascript code to receive a date, an option would be to issue the code that creates a date:
preencheform_edicaoJS(..., new Date('<?php echo $dta_inicial; ?>'))
Which works, but only if the date is in month/day/year format:
preencheform_edicaoJS(..., new Date('17/12/2015')) // Invalid Date
So I suggest simply pass the data as the same string and deal with the format in the Javascript function itself (unless you find it easier to do this in PHP, your criterion):
preencheform_edicaoJS(...,'<?php echo $dta_inicial; ?>')
(Note the use of single quotes, it is not to conflict with the calling code, which uses double quotes - onclick="preencheform_edicaoJS(...)"
)
Updating: if what you want in Javascript is a string (i.e. a representation of a date, not an object Date
), but in a different format than its variable $dta_inicial
has, it is necessary to convert string to date and then format the date again to string.
This can be done in a "formal" way (using methods that deal with dates, in one or another language, such as pointed in comment), but being a simple format you can also do manually, kind like this:
$dta_array = explode("/", $dta_inicial);
$dta_transformada = $dta_array[2] . "-" . $dta_array[1] . "-" . $dta_array[0];
...
preencheform_edicaoJS(...,'<?php echo $dta_transformada; ?>')
(invert the indexes 1
and 0
if the date is originally in the month/day/year format)
Or on the Javascript side:
var arr = data.split('/');
var str = arr[2] + "-" + arr[1] + "-" + arr[0];
What is the date format? If it’s XX/XX/XX, I think JS is splitting with the date, so 0.232xxxx... Try to put
<?php echo "$dta_inicial"; ?>
... with"
...– gustavox
@gustavox I think you correctly identified the problem. But the quotes are to be inside the
echo
or out? And by the way, in case they need to be simple quotes, otherwise it will conflict with the calling code.– mgibsonbr
You’re right @mgibsonbr, the quotes got in the wrong place, and they should be really simple... it was inattention, but this is not even a question I thought I could answer, because as much as I identified the problem, I wouldn’t know how to explain the solution (though the quotes were right hehe) with the perfection you made. + 1 Think of my comment above as an enthusiast’s ball roll to the expert (who he knew was right behind). : -) +1
– gustavox