hackersleepyhead
Protobuf NaiveDateTime type
Hello,
what would be the best type for proto3 to handle NaiveDateTime from Elixir types.
message PostResponse {
string content = 1;
string id = 2;
google.protobuf.Timestamp inserted_at = 3;
google.protobuf.Timestamp updated_at = 4;
string user_id = 5;
}
I think Timestamp is not the best one, I want to have the NativeDateTime type value as it is.
any help would be appreciated.
First Post!
dimitarvp
Well, NaiveDateTime is just a struct / map after all:
iex(1)> NaiveDateTime.now() |> Map.keys()
[:__struct__, :calendar, :day, :hour, :microsecond, :minute, :month, :second,
:year]
The calendar field is usually the module/atom Calendar.ISO so you can strip it if you don’t deal with other calendars, and the special __struct__ field, and then end up with this:
iex(2)> NaiveDateTime.utc_now() |> Map.from_struct() |> Map.drop([:__struct__, :calendar])
%{
day: 10,
hour: 12,
microsecond: {981284, 6},
minute: 32,
month: 3,
second: 40,
year: 2021
}
You can then also remove the decimal precision value from microsecond by using elem(..., 0) and then you’ll just have seven unsigned 32-bit integers (which you can encode with int32 since it uses variable-length encoding over the wire). That resulting map of seven integers can then very easily be described as a nested Protobuf structure afterwards.
Of course, you can also convert the NaiveDateTime to UNIX seconds / milliseconds / microseconds / nanoseconds and just encode the whole thing as a 64-bit unsigned integer:
naive_date_time_from_another_function
|> DateTime.from_naive!("Etc/UTC") # assuming your times are in UTC
|> DateTime.to_unix(:microsecond) # or :second, or :millisecond, or :nanosecond)
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









