Search code examples
rubydatetimeactiverecordfixtures

Datetime string format for ActiveRecord fixture (non-Rails)


Rails apparently provides an extension to Time.to_s allows you format the timestamp in a database-friendly way, e.g. Time.now.to_s(:db). This can be used in an ActiveRecord dynamic fixture:

my_record:
  some_datetime: <%= Time.utc(2015, 1, 1).to_s(:db) %>

However, outside Rails, this fails with

ArgumentError: wrong number of arguments (1 for 0)
  (...) in `to_s'

If I'm going to convert the time by hand, what is the format (with time zone etc.) I should be using here?

Alternatively, if I'm wrong and it's not Rails but something in ActiveRecord that adds this extension, what do I need to require to get it?


Solution

  • The format is like this: YYYY-MM-DD HH-MM-SS

    Another way to get that format is with strftime:

    DateTime.now.strftime('%Y-%m-%d %I:%M:%S')
    

    If you want the include timezone, add %z:

    DateTime.now.strftime('%Y-%m-%d %I:%M:%S %z')