Date to string "result of (time.Time).String call not used"

I want yesterday as a string. ‘2022-04-11’ to use in a SQL query, but I get an error:

result of (time.Time).String call not used

https://play.golang.com/p/RnzVlepoV6x

package main

import (
	"fmt"
	"time"
)

func main() {
	date := time.Now().Add(-24 * time.Hour)
	date.Format("2006-01-02")
	date.String()
	fmt.Println(date)
}

What am I doing wrong?

You are not usint the result of date.String().

This method does not change the type of date in place, but instead creates a string you then can use.

Though fmt.Println() will call the String() method anyway, therefore its not necessary for you do call it manually.

Also Format() will not make the date remember the requested format, it will just return the formatted string.

So what you actually want to do is probably this:

package main

import (
	"fmt"
	"time"
)

func main() {
	date := time.Now().Add(-24 * time.Hour)
	fmt.Println(date.Format("2006-01-02"))
}
3 Likes

I want the date as string that can be used in a SQL query. This is a simplified pseudo code that not works :slight_smile:

This works with strings, but not with date format.

func main() {
	date := time.Now().Add(-24 * time.Hour)
	date = date.Format("2006-01-02")
	
    query := "SELECT * FROM users WHERE usr_edit = $1"
    db.Query (query, date) <--------------date as "string"?
}

You should be able to use a date directly in your SQL query. That looks like postgres. Have you tried something like this?

In your case it would look more like:

date := time.Now().Add(-24 * time.Hour)
rows, err := db.Query (`SELECT * FROM users 
WHERE date_trunc('day', $1) = date_trunc('day', usr_edit)`, date)

Or something along those lines. Though since this has to do table scan it’s not super efficient. I generally prefer to do BETWEEN approach. But this should get you started. Also do you even need to pass in a time.Time? You could do this with just sql:

rows, err := db.Query (`SELECT * FROM users 
WHERE date_trunc('day', now() - interval '1 day') = date_trunc('day', usr_edit)`)

… and if you want to go with BETWEEN approach to avoid table scan:

rows, err := db.Query (`
SELECT * FROM users 
WHERE usr_edit 
    BETWEEN date_trunc('day', now() - interval '1 day') 
    AND date_trunc('day', now())`)
1 Like

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