在Elixir / Phoenix中,如何设置日期时间字段而不任何其他依赖项? Postgresql中字段的类型是timestampz,我想将其显示为“05,Dec,2015”。
答案 0 :(得分:2)
这是一种方式:
def format_datetime(%Ecto.DateTime{day: day, month: month, year: year}) do
"#{format_day(day)}, #{format_month(month)}, #{year}"
end
defp format_day(day) when day < 10, do: "0#{day}"
defp format_day(day), do: "#{day}"
defp format_month(1), do: "Jan"
defp format_month(2), do: "Feb"
defp format_month(3), do: "Mar"
defp format_month(4), do: "Apr"
defp format_month(5), do: "May"
defp format_month(6), do: "Jun"
defp format_month(7), do: "Jul"
defp format_month(8), do: "Aug"
defp format_month(9), do: "Sep"
defp format_month(10), do: "Oct"
defp format_month(11), do: "Nov"
defp format_month(12), do: "Dec"
测试:
iex(1)> format_datetime(%Ecto.DateTime{day: 5, month: 12, year: 2015})
"05, Dec, 2015"
答案 1 :(得分:1)
您可以非常轻松地推出自己的解决方案,但您需要拥有月份名称列表:
defmodule DateTimeFormat do
@months %{1 => "Jan", 2 => "Feb", 3 => "Mar", 4 => "Apr",
5 => "May", 6 => "Jun", 7 => "Jul", 8 => "Aug",
9 => "Sep", 10 => "Oct", 11 => "Nov", 12 => "Dec"}
def format(timestamp) do
'~4..0B, ~ts, ~2..0B'
|> :io_lib.format([timestamp.year, @months[timestamp.month], timestamp.day])
|> List.to_string
end
end
或者,您可以直接在Postgres中进行格式化。这是否实用将取决于您的使用案例,但我发现它非常有用,例如使用单个查询生成报告:
to_char(my_column, 'MM, Mon, YYYY')