[Golang] Find Files After Given Time


This post shows you how to find files after a given timestamp in Go. We use filepath.Walk to access all files in a directory and use Time.After to check if the modified time of the file is after or not.

If you want to find files before given time, use Time.Before instead.

You can also use shell command to do this [1] [2], but I like to code in Go because it is more readable.

package main

import (
      "fmt"
      "os"
      "path/filepath"
      "time"
)

func FindFilesAfter(dir string, t time.Time) (paths []string, infos []os.FileInfo, err error) {
      err = filepath.Walk(dir, func(p string, i os.FileInfo, e error) error {
              if e != nil {
                      return e
              }

              if !i.IsDir() && i.ModTime().After(t) {
                      paths = append(paths, p)
                      infos = append(infos, i)
              }
              return nil
      })
      return
}

func checkFile(path string, info os.FileInfo) {
      fmt.Println(path)
      fmt.Println(info)
}

func main() {
      dir := "path/to/your/dir"
      t, err := time.Parse("2006-01-02T15:04:05-07:00", "2018-04-07T05:48:03+08:00")
      if err != nil {
              panic(err)
      }
      paths, infos, err := FindFilesAfter(dir, t)
      if err != nil {
              panic(err)
      }
      for i, _ := range paths {
              checkFile(paths[i], infos[i])
      }
}

Tested on: Ubuntu Linux 17.10, Go 1.10.1

References

[1]
[2]