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.

1
  • did either of the answers resolve your issue? Commented Apr 10, 2012 at 0:53

2 Answers 2

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.
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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! :)
No worries - it's not like I need the rep. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.