Converting unix timestamp before sending it by json

Go To StackoverFlow.com

1

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.

2012-04-04 22:57
by moonwalker
did either of the answers resolve your issue - dragon 2012-04-10 00:53


2

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:

  1. It keeps the payload low, since you're transferring an integer and not a string.
  2. It enables you to use the timestamp in different ways on the client without having to parse it again. e.g. Date.now()/1000 - post.date will give you the number of seconds since the post was created, and so on.
  3. UNIX timestamp is not timezone-sensitive. When rendered on client, it'll be in the local timezone and format. If you render it on the server, it'll be in server's timezone and use server's locale settings.
2012-04-04 23:02
by dragon


2

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.

2012-04-04 23:02
by Amber
I want to pick them both as the best answer, but unfortunately I can't! So thanks both for your answers. This helped me solve my problem! : - moonwalker 2012-04-20 16:43
No worries - it's not like I need the rep. : - Amber 2012-04-20 16:44
Ads