How to get begin and end of current day (Date Time)

I need to get the start and end of the current day, I solved this, but maybe someone knows a better solution?
Task to write functions:
getBeginOfDay:
2021-01-01T14:30:25+02:00 → 2021-01-01T00:00:00+02:00
getEndOfDay:
2021-01-01T14:30:25+02:00 → 2021-01-01T23:59:59+02:00

getBeginOfDay:

q.Lambda('date', q.Let({
    year: q.ToString(q.Year(q.Var('date'))),
    month: q.Let({
      monthNumber: q.Month(q.Var('date')),
    }, q.If(
      q.LT(q.Var('monthNumber'), 10),
      q.Concat(['0', q.ToString(q.Var('monthNumber'))], ''),
      q.ToString(q.Var('monthNumber')),
    )),
    day: q.Let({
      dayNumber: q.DayOfMonth(q.Var('date')),
    }, q.If(
      q.LT(q.Var('dayNumber'), 10),
      q.Concat(['0', q.ToString(q.Var('dayNumber'))], ''),
      q.ToString(q.Var('dayNumber')),
    )),
  }, q.ToTime(q.Date(q.Concat([q.Var('year'), q.Var('month'), q.Var('day')], '-')))))

Get start day is similar. It looks bulky, and not solved problem with time zone.
Looking for solution based on TimeDiff TimeSubstract, but can’t come up with yet.

When you convert a Time to a Date, the time portion is truncated, so converting back to Time gives you the start of a date. Adding 86399 seconds to the start of the day gets you the end of the day.

Let({
  time: Now(),
},
  {
    begin: ToTime(ToDate(Var("time"))),
    end: TimeAdd(ToTime(ToDate(Var("time"))), 86399, "seconds"),
  }
)

Dealing with time is really complicated, and I wish Fauna had more functions for dealing with it. There are scary edge cases like leap-seconds which might break the assumption about how many seconds you need to add. If there were functions like StartOfDay or EndOfDay, or basically the entirety of the date-fns library in Fauna I would be so happy.

1 Like

Excellent point!

You can add 1 day and subtract 1 second:

TimeSubtract(TimeAdd(ToTime(ToDate(Var("time"))), 1, "day"), 1, "second")

That’s still pretty verbose and I think your point stands that having simpler functions is a a really-nice-to-have.

I don’t know if such functions belong in the “standard library” of FQL functions. We are trying to make it more dead simple to add/include FQL “libraries” to your own databases. For example, you can currently use fauna-schema-migrate to import utility packages. Imagine an fql-date-fns npm package and including the functions that you need:

// fauna/StartOfDay.js
import { StartOfDay } from 'fql-date-fns'
export default StartOfDay
// use the new UDF
Call("StartOfDay", Now())

Things I know I want to see:

  • fauna-schema-migrate able to migrate multiple resources from a single file (This is on the roadmap, in fact). For example, I mean doing this to avoid having to create many files: import * as dateFns from 'fql-date-fns'; export default dateFns.
  • similar ecosystems for other languages, not just javascript.
2 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.