Skip to content
Advertisement

Convert date into sfdate for snowflake

I’m having problems working with dates in Snowflake using Snowflake’s Javascript.

One select queries and gets a date. It’s declared in the source table as a date. I want to be able to add 1 day to this date, then insert that into a DATE field in another table. However, I’m getting a bind error on this. With help from another stackoverflow, I got the returned type and found it to be a string, and not an sfDate.

How can I convert the returned string from a select into a date that I can work with? A bonus question is how can I add one day to this value?

Also tried to convert it to date with try_to_date as below:

and without it:

and I get

in both cases

Advertisement

Answer

The default JavaScript Date.toString() representation converts the date to a string in a format that is non-standard. Also, to use a Date constructor ensure you pass the new keyword as otherwise Date acts as a function that rejects invalid inputs and silently returns the current date.

When using the default Date string formatting from JavaScript in SQL to be cast as date or timestamp types, Snowflake only recognises standard formatted strings, and will reject JS date strings of the form Sun Jul 29 2018 00:00:00 GMT-0700 (PDT). Use Date.toISOString() instead to produce a usable representation that will work with Snowflake SQL types.

Furthermore, the binds argument in snowflake.createStatement(…) must always be an array of elements, even when you are planning to pass only a single element to it. That is, supply binds: [convertedRunningDate] instead of binds: convertedRunningDate.

Combining the two above points, here’s an example that shows how to manipulate the date within JavaScript from one table to another.

This yields the result:

If you need to arbitrarily use Date objects instead of sourcing it from a table row, just ensure you are constructing them properly (with new), and when binding use its Date.toISOString() method instead of passing it as-is (default toString() produces an incompatible format).

Note: Where possible, try to manipulate it over SQL and just extract results so you do not have to work with two different date/time type systems.

Further reading:

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement