【问题标题】:Phoenix.HTML.Form and formatting a Timex.DateTime for a text inputPhoenix.HTML.Form 并为文本输入格式化 Timex.DateTime
【发布时间】:2017-04-23 14:51:14
【问题描述】:

我想将 Timex DateTime 字段的格式更改为单个文本输入。当我让 Phoenix 处理格式时,它看起来像这样:

2017-04-06 23:03:44.513454+10:00 AEST Australia/Hobart

请注意,我使用的是 use Timex.Ecto.Timestamps, usec: true - 所以它包括微秒。

这是我想要的样子:

2017-04-06 23:03:44 +10:00

有没有办法通过text_input标签来控制日期的格式?还是有其他方法可以做到这一点?

这是我正在使用的架构:

schema "log" do
  field :start_date, Timex.Ecto.DateTime
  field :end_date, Timex.Ecto.DateTime
  field :comment, :string

  timestamps
end

我的表单看起来像这样:

<%= form_for @changeset, @action, fn f -> %>
  <%= if @changeset.action do %>
    <div class="alert alert-danger">
      <p>Oops, something went wrong! Please check the errors below.</p>
    </div>
  <% end %>

  <div class="form-group">
    <%= label f, :start_date, class: "control-label" %>
    <%= text_input f, :start_date, class: "form-control" %>
    <%= error_tag f, :start_date %>
  </div>

  <div class="form-group">
    <%= label f, :end_date, class: "control-label" %>
    <%= text_input f, :end_date, class: "form-control" %>

    <%= error_tag f, :end_date %>
  </div>

  <div class="form-group">
    <%= label f, :comment, class: "control-label" %>
    <%= textarea f, :comment, class: "form-control" %>
    <%= error_tag f, :comment %>
  </div>

  <div class="form-group">
    <%= submit "Submit", class: "btn btn-primary" %>
  </div>
<% end %>

【问题讨论】:

  • text_input f, :start_date, class: "form-control", value: %{input_value(f, :start_date) | microsecond: {0, 0}} 怎么样?
  • ex(9)> Timex.format!(Timex.now(), "%F %T %:z", :strftime) => "2017-04-19 15:44:01 +00:00"
  • 我没有意识到input_value 的存在。这解决了我的问题

标签: elixir phoenix-framework


【解决方案1】:

您可以使用Phoenix.HTML.Form.input_value/2 获取输入的值,并且可以通过将value: ... 传递给text_input 来指定要显示给用户的值。将此与从值中删除微秒相结合,您将获得相同格式的时间,而无需任何微秒:

text_input f, :start_date, class: "form-control", value: %{input_value(f, :start_date) | microsecond: {0, 0}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多