First of all thanks for taking the time to look into this.
I store the date in my database as a unix timestamp and when I get all the info using:
while($row = mysql_fetch_assoc($result)) {
$posts[] = $row;
}
/* return the posts in the JSON format */
return json_encode($posts);
The date is available only as a unix timestamp when I try to get it using the following:
var postHandler = function(postsJSON) {
$.each(postsJSON,function(i,post) {
alert(post.date);
}
}
Is there a way to convert it to readable date before sending it by JSON? Or even afterwards?
Thanks a lot for your help.
Use the Date object in JavaScript.
alert(new Date(post.date))
Note: It's the best to pass it all the way in UNIX timestamp format until rendered, because:
Date.now()/1000 - post.date
will give you the number of seconds since the post was created, and so on.Sure, from the PHP side you could do it like this:
while($row = mysql_fetch_assoc($result)) {
$row['your_date_field'] = date('r', $row['your_date_field']);
$posts[] = $row;
}
(You can customize the format string passed to date()
as you please; 'r'
was just a simple default.)
From the Javascript side, you could do it like this:
new Date(post.date);
which when rendered to a string will format as the default date format, or you can use other methods on the Date
object to get other formats.
Which method you use is up to you, but as dragon points out, doing it client-side is often nicer since it both reduces data transmitted and gives you more flexibility without having to parse a string.