Home > Mobile >  GOLANG - Find files created between a date range
GOLANG - Find files created between a date range

Time:11-28

I'd like to know how to find files in a specific folder between a date range. For example: I want to find all files in folder X that were created between 01-Aug-13 and 31-Aug-13.

I tried this:

dir := "path/to/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])
}

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
}

CodePudding user response:

Hope the following answer is what you are looking for.

  • If your point of question is more about time range you can using function Before and After from time package
  • If your point of question is more about finding create time instead of modifying time. you can consider package syscall to find atime, mtime, and ctime - in essence those are:

atime (access time) is the file access time

mtime (modify time) is the file modify time

ctime (change time) is the inode or file change time

package main

import (
    "io/fs"
    "log"
    "os"
    "syscall"
    "time"
)

func main() {
    // prepare data
    start, _ := time.Parse(time.RFC3339, "2022-11-26T07:04:05Z")
    end, _ := time.Parse(time.RFC3339, "2022-11-26T08:10:00Z")
    var dir = "your path"

    files := FindFilesByDateRange(dir, start, end)

    // print result
    log.Printf("file range: %s-%s\n", start.Format(time.RFC3339), end.Format(time.RFC3339))
    for _, f := range files {
        log.Println(f.Name())
    }

}

func FindFilesByDateRange(dir string, start, end time.Time) []fs.FileInfo {
    fileSystem := os.DirFS(dir)
    var files []fs.FileInfo
    if err := fs.WalkDir(fileSystem, ".", func(path string, d fs.DirEntry, err error) error {
        if err != nil {
            log.Fatal(err)
        }
        fileInfo, err := d.Info()
        if err != nil {
            return err
        }
        stat := fileInfo.Sys().(*syscall.Stat_t)
        cDate := time.Unix(stat.Ctimespec.Sec, stat.Ctimespec.Nsec).UTC()
        if !d.IsDir() && (cDate.After(start) && cDate.Before(end)) {
            files = append(files, fileInfo)
        }
        return nil
    }); err != nil {
        return nil
    }
    return files
}
  • Related