lsaville

lsaville

Problem trying to call Ecto.DateTime.to_iso8601

Hi everyone!

I’m trying to follow the tutorial from thoughtbot here to create my first phoenix json api endpoint. The code for the test is following:

# Create this test in test/controllers/todo_controller_test.exs
defmodule Todos.TodoControllerTest do
  use Todos.ConnCase

  test "#index renders a list of todos" do
    conn = build_conn()
    todo = insert(:todo)

    conn = get conn, todo_path(conn, :index)

    assert json_response(conn, 200) == %{
      "todos" => [%{
        "title" => todo.title,
        "description" => todo.description,
        "inserted_at" => Ecto.DateTime.to_iso8601(todo.inserted_at),
        "updated_at" => Ecto.DateTime.to_iso8601(todo.updated_at)
      }]
    }
  end
end

When I run the test I get the following error:

 ** (FunctionClauseError) no function clause matching in Ecto.DateTime.to_iso8601/1
     stacktrace:
       (ecto) lib/ecto/date_time.ex:584: Ecto.DateTime.to_iso8601(~N[2017-03-23 19:55:47.300335])
       test/controllers/todo_controller_test.exs:14: (test)

I’ve completed the tutorial up to the point where this should be passing. If I change the test so that I’m not attempting to format the date I get the following:

     Assertion with == failed
     code: json_response(conn, 200) == %{"todos" => [%{"title" => todo.title(), "description" => todo.description(), "inserted_at" => "Frank", "updated_at" => "Frank"}]}
     lhs:  %{"todos" => [%{"description" => "List of steps I need to complete", "title" => "Something I need to do", "inserted_at" => "2017-03-23T19:56:39.484442", "updated_at" => "2017-03-23T19:56:39.497129"}]}
     rhs:  %{"todos" => [%{"description" => "List of steps I need to complete", "title" => "Something I need to do", "inserted_at" => "Frank", "updated_at" => "Frank"}]}
     stacktrace:
       test/controllers/todo_controller_test.exs:10: (test)

Which seems to make sense. The problem is with Ecto.DateTime.to_iso and it’s no matching clause. The ecto code is this:

  def to_iso8601(%Ecto.DateTime{year: year, month: month, day: day,
                                hour: hour, min: min, sec: sec, usec: usec}) do
    str = zero_pad(year, 4) <> "-" <> zero_pad(month, 2) <> "-" <> zero_pad(day, 2) <> "T" <>
          zero_pad(hour, 2) <> ":" <> zero_pad(min, 2) <> ":" <> zero_pad(sec, 2)

    if is_nil(usec) or usec == 0 do
      str
    else
      str <> "." <> zero_pad(usec, 6)
    end
  end

So possibly the ~N[2017-03-23 19:57:48.500354] is not matching with the

%Ecto.DateTime{year: year, month: month, day: day,
               hour: hour, min: min, sec: sec, usec: usec}

in the ecto code? It is probably something small that I’m unaware of but I’ve very new to elixir and phoenix and would appreciate any advice on how to resolve this. Thanks so much for your time!

Most Liked

gon782

gon782

I believe it’s the default timestamp type used by Ecto. You should be able to set it in your schema by using the following in your schema:

@timestamps_opts [type: :utc_datetime]

You can find more info here.

The difference being that DateTime (which corresponds to :utc_datetime) provides timezone info, which makes it more usable for conversions, etc.

There have been some great talks and work on this by Lau Taarnskov ((“lau” on GitHub). I recommend them, as it’s a surprisingly interesting area with a lot of pitfalls.

lsaville

lsaville

Great info thanks so much. I can see now how I got myself into the confusion by using timestamps which defaults to NaiveDateTime

gon782

gon782

Having looked at it only a little bit it seems you’re creating a NaiveDateTime and what this function is looking for is actually a DateTime.

Ecto.DateTime has a function called cast/1 that you can use to convert it to an actual DateTime. You can then pass that to the function you’re trying to use. Note, though, that what you have in your sigil is what you’re going to get back.

Also, I have to ask: Who is Frank and how did he end up in your {inserted,updated}_at fields?

Where Next?

Popular in Questions Top

_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29703 241
New
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36432 110
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement