简体   繁体   中英

Rails: Get the DateTime format returned using Jbuilder

I noticed when returning a field with type datetime in jbuilder I get something like this : "2016-11-25T13:25:06.024Z"

But when in a .html.erb page I display this field I get something like this "2016-12-21 09:35:05 UTC"

My question is how to get the format of JBuilder in html.erb.

What you're seeing in your JSON is a standard ISO-8601 formatted timestamp for a time in UTC (hence the Z ). You can get this format in Rails by the conveniently named iso8601 method:

> Time.now.utc.iso8601
 => "2016-12-22T04:59:25Z" 

The utc call is there to ensure that the time is in UTC, you probably don't need it but it doesn't hurt and can prevent problems.

If you want to match the precision that you're getting from Jbuilder, include the precision in the iso8601 call:

> Time.now.utc.iso8601(3)
 => "2016-12-22T05:01:21.512Z" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM