file_name_util.go 788 B

12345678910111213141516171819202122232425262728
  1. package util
  2. import (
  3. "regexp"
  4. "strconv"
  5. "time"
  6. )
  7. const FileNameFormatStr = "2006-01-02-15-04"
  8. // FileNameBeforeDays 查找文件名中有多少在指定天数之前的
  9. func FileNameBeforeDays(days int, fileNames []string) []string {
  10. oldFiles := make([]string, 0)
  11. // 2006-01-02-15-04
  12. fileRegxp := regexp.MustCompile(`([\d]{4})-([\d]{2})-([\d]{2})-([\d]{2})-([\d]{2})`)
  13. subDuration, _ := time.ParseDuration("-" + strconv.Itoa(days*24) + "h")
  14. before := time.Now().Add(subDuration)
  15. for i := 0; i < len(fileNames); i++ {
  16. dateString := fileRegxp.FindString(fileNames[i])
  17. if dateString != "" {
  18. if fileTime, err := time.Parse(FileNameFormatStr, dateString); err == nil && fileTime.Before(before) {
  19. oldFiles = append(oldFiles, fileNames[i])
  20. }
  21. }
  22. }
  23. return oldFiles
  24. }