Reputation: 313
I want to get an date input from user and compare(if it is at least 30min future) it whether it is future and save it to database. Date from user input is like this 2018-09-26 Time from user input is like this 16:00 So I convert it to naive datetime
def build_naive_datetime(date, time) do
{:ok, datetime} = NaiveDateTime.from_iso8601("#{date} #{time}:00")
datetime
end
so it returns ~N[2018-09-26 16:00:00]
.
and I want to compare it.
def schedule_datetime_is_future?(schedule_datetime) do
# 30 mins future from now on
future_datetime = DateTime.to_naive(Timex.add(Timex.now, Timex.Duration.from_minutes(30)))
case Timex.compare(schedule_datetime, future_datetime) do
1 ->
# schedule datetime is future
true
-1 ->
# schedule datetime is not future
false
_ ->
false
end
end
But Timex.now returns in my dev computer time zone time(maybe returns utc). So compare doens't work properly.(user input datetime is local time.) How can I do this in better way? Do I have to change user datetime to utc time? How can I do this?
Thanks
Upvotes: 1
Views: 609
Reputation: 121000
You should not convert anything to NaiveDateTime
in the first place since naïve date time does not have a time zone at all (hence the name.)
You probably should use DateTime.diff/3
:
def build_datetime(date, time) do
with {:ok, datetime, 0} <- DateTime.from_iso8601("#{date}T#{time}:00Z"),
do: datetime
end
def schedule_datetime_is_future?(schedule_datetime) do
DateTime.diff(schedule_datetime, DateTime.utc_now) > 30 * 60
end
Upvotes: 2