How to find how much days left in a date

Hello, i have an date string. it can be past date, future date or present date. i want to compare it to current time.
Suppose, current date is 2021-06-17 and the date string is 2021-06-15
then it should return me -2, if date gone then it should return in -minus.
Suppose, current date is 2021-06-17 and the date string is 2021-06-19
then it should return 2.
I hope you’re understood.
actually i want to do

if daysleft <= 3 {
    }

i have my code which isn’t working perfectly, like if date is gone then it will also return an positive integer. like current date is 2021-06-17 and the date string is 2021-06-19 then it will return 2 and if date string is 2021-06-15 then it will also return 2, it should return -2.

here are my codes :

package main

import (
	"fmt"
	"time"
)

func main() {
	days := daysBetween(time.Now(), date("2021-06-02"))
	fmt.Printf("%d\n", days)
	t, _ := time.Parse("2006-01-02", "2021-06-02")
	if days <= 3 {
		fmt.Printf("%s", t.AddDate(0, 0, 5))
	}
}

func date(s string) time.Time {
	d, _ := time.Parse("2006-01-02", s)
	return d
}
func daysBetween(a, b time.Time) int {
	if a.After(b) {
		a, b = b, a
	}

	days := -a.YearDay()
	for year := a.Year(); year < b.Year(); year++ {
		days += time.Date(year, time.December, 31, 0, 0, 0, 0, time.UTC).YearDay()
	}
	days += b.YearDay()

	return days
}

can someone tell a solution?

Actually, we have two files.
expire.txt
back.txt

our program will read a expire date from expire.txt file and then compare it with current time. if 3 or less days left for the expire then the program will substract 5 days from the expire date and and store the result in back.txt

i hope you understood, please help me with this

It could be something like this

package main

import (
“fmt”
“time”
)

func daysBetween(a, b time.Time) int {
fmt.Printf(“a=%d-%d-%d b=%d-%d-%d\n”, a.Year(), int(a.Month()), a.Day(), b.Year(), int(b.Month()), b.Day())
days := a.Sub(b).Hours() / 24
if days < 0 {
days *= -1
}
return int(days)
}

func main() {
dt := time.Now()
t1 := Date(dt.Year(), int(dt.Month()), dt.Day())
t2 := Date(2009, 11, 9)
days := daysBetween(t1, t2)
fmt.Println(days)
}

func Date(year, month, day int) time.Time {
return time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC)
}

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