在Ecto.DateTime和DateTime之间转换

时间:2017-02-08 03:59:45

标签: datetime elixir phoenix-framework ecto

我在Ecto.DateTime中有一个日期时间,在DateTime中有第二个日期时间。我怎样才能将它们互相转换?难道没有一种简单的方法没有外部依赖?文档中没有任何内容。其中一个有to_erl,另一个是from_unix,但方法中没有重叠,例如to_unix / from_unix或to_erl / from_erl或类似的东西。

1 个答案:

答案 0 :(得分:11)

相当于@Override public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view RelativeLayout v = (RelativeLayout) LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_recycle_layout, parent, false); TextView txtView = (TextView) v.findViewById(R.id.my_text_view); .... .... ViewHolder vh = new ViewHolder(v); return vh; } Ecto.DateTime,因为它们都没有存储时区,而NaiveDateTime则存储时区。 Erlang日期时间也没有时区,这就是DateTime中没有to_erlfrom_erl的原因。

您可以先转换为DateTime,然后使用NaiveDateTime以及日期时间所在的时区(Elixir仅支持DateTime.from_naive/2,自Elixir 1.4起):

Etc/UTC

如果您之前使用的是iex(1)> Ecto.DateTime.utc |> Ecto.DateTime.to_erl |> NaiveDateTime.from_erl! |> DateTime.from_naive!("Etc/UTC") %DateTime{calendar: Calendar.ISO, day: 8, hour: 4, microsecond: {0, 0}, minute: 49, month: 2, second: 9, std_offset: 0, time_zone: "Etc/UTC", utc_offset: 0, year: 2017, zone_abbr: "UTC"} iex(2)> DateTime.utc_now |> DateTime.to_naive |> NaiveDateTime.to_erl |> Ecto.DateTime.from_erl #Ecto.DateTime<2017-02-08 04:50:23> ,那么您现在可能想要使用Ecto.DateTime