简体   繁体   中英

How to truncate a date to the first day of the month in Snowflake?

I am not able to find any good conversion code to get 2014-02-17 into 2014-02-01 without having to use concatenation and a ton of formatting. I wonder if someone can help me find a good command to achieve this. Thanks!

Snowflake supports date_trunc() for datatypes DATE , TIME , and TIMESTAMP :

SELECT DATE_TRUNC(month, CURRENT_DATE()) AS first_day_of_month;

Sounds like you're working with strings. If that's the case and they'll always be in the format 'yyyy-MM-dd', you can just take the first 8 characters and add '01':

left(MyStringValue, 8) + '01'

If you're working with date fields, I like the trick of doing datediff to get the months from 0, then use dateadd with 0 to get back to the first of the month:

dateadd(month, datediff(month, 0, MyDateValue), 0)

This is another option:

SELECT TRUNCTIMESTAMPTOMONTH(CURRENT_DATE());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM