Question

I need to produce a date in Rails which looks like this:

/Date(1294268400000)/

I have tried various combinations of DateTime, to_i, to_json but never managed to get the /Date()/ thing.

Do I have to simply get my date in ms and then wrap the /Date(and )/ manually, or is there a built in method?

Was it helpful?

Solution

What about (ruby 1.9.x)?:

Time.now.strftime("/Date(%s%L)/")
=> "/Date(1335280866211)/"

OTHER TIPS

You should try

new Date(posixMillisecondsHere)

first. MDN says that calling the Date function outside of the constructor context (i.e., without the new) will always return a string containing a formatted date rather than a Date object.

Strictly speaking, when you do that, you are writing JavaScript and not JSON. JSON cannot contain Date objects.

RFC 4627 says

2.1. Values

A JSON value MUST be an object, array, number, or string, or one of the following three literal names:

 false null true

If you want to put a Date into what is strictly considered JSON and then get it back out, you must choose some way of using the JSON primitives (to wit, objects, arrays, numbers, strings, etc.) to encode a Date.

If you want to get a Date back out of JSON, whatever parses your JSON must understand the convention that you used to encode the Date.

Hope these are credible and/or official enough to help.

What about something like this:

in your config/en.yml file:

en:
  time:
    formats:
      json: "/Date(%s%L)/"

and than in the view:

<%= l(Time.now, :format => :json) %>

Please note that you would need access to the helpers in the method that renders json. So it won't work if you are using ActiveRecord#to_json method for generating jsons.

Check out this question:

c# serialized JSON date to ruby

... simple answer seems to be to create a parse_date method.

It's the UNIX Epoch (seconds since 1970-01-01) right? What about using DateTime#strftime method?

# Taken from the Ruby documentation
seconds_since_1970 = your_date.strftime("%s")

UPDATE: OK, it's milliseconds, according to the documentation you can use your_date.strftime("%Q") to get the ms (but I've not tried yet).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top