[RUBY] How to display today's date and time by default: Remove seconds or less

【Overview】

1. Conclusion </ b>

2. How to describe </ b>

3. What I learned from here </ b>

  1. Conclusion

Use (arbitrary variable) .toISOString (). slice (0, -8) </ b>

  1. How to describe

As a premise

ruby:new.html.erb


<%= f.datetime_field :study_date ,id:"datetime_field"%>

It is set in.

datetime_field method = ***. ToISOString (). Slice (0, -8); You can default to today's year, month, hour, and minute.

ruby:***.html.erb


<script>
  var today_time = new Date();
   now.setMinutes(today_time.getMinutes() - now.getTimezoneOffset()); #----❶
    document.getElementById('datetime_field').value = today_time.toISOString().slice(0, -8); #----❷
</script>

I described it. Since it is described in html.erb, it is enclosed in "script", and when it is updated, an error occurs if the variable is defined in console, so it is set to var. For ❶ and ❷, the time displayed as mentioned in the URL below is in UTC (❷), so it is adjusted to the UTC difference (❶) in advance.

** Referenced URL: ** ** HTML5 To set the current time
**

  1. What I learned from here

I am the first

ruby:****.html.erb


<f.date_field :****, value:Time.now.strftime("%Y-%m-%d")>

Was using. If you enter value: Time.now.strftime ("% Y-% m-% d"), the current date will be automatically entered when the page is displayed.

** URL that was quite helpful: ** ** Set default value in Rails date_field **

However, in the case of f.datetime_field, if you put the above in value or set it to Time.now

python


The specified value "2020 9/16 12:05" does not conform to the required format.  The format is "yyyy-MM-ddThh:mm" followed by optional ":ss" or ":ss.SSS".

I got out. It was not recognized because it did not meet the standard description. So I did it the above way, but realized that I didn't really understand slice (0, -1). Since slice (start, end) extracts only a few minutes before the character ~ end starting from start, "ss.SSS (time less than a second)" could be omitted by writing as above.

** Referenced URL: ** ** slice method **


Recommended Posts