When should i use DateTime vs date, time fields in ruby/rails?

前端 未结 1 1673
陌清茗
陌清茗 2021-01-17 10:28

I currently have separate game_date and game_time fields and I am having a hell of a time comparing my DateTime.now to a concatenated DateTime because of time zone issues.

相关标签:
1条回答
  • 2021-01-17 11:04

    The general idea is to use a DateTime as a general purpose representation of time. Where you might be confused is that Time also includes a date component as it is an encapsulation of the UNIX time_t concept of seconds since epoch, or UNIX_TIME() in MySQL terms.

    As I explain in another answer, Time is a more limited representation than DateTime and can only represent dates and times up to Jan 18, 2038. A DateTime can represent 4,712 BCE as well as 21,000 years in the future.

    If you want a separate field that represents time of day, which it seems like you might want here, you should create a single numerical field that represents either seconds past midnight if that kind of precision is required, or a more convenient "HHMM" representation that doesn't concern itself with the differences between base-60 and base-10.

    Another alternative is to have two fields, one being a DateTime and one being a Date. If you're creating a calendar entry with no particular time, populate only the Date field. If it has a time, populate both.

    Remember that a date field is populated with a literal date and does not concern itself with time zones, so this can cause trouble if it is not expressed in the user's local time. A DateTime can always be converted to a user's local time if required.

    0 讨论(0)
提交回复
热议问题