github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/timex/javafmt.go (about)

     1  package timex
     2  
     3  import (
     4  	"regexp"
     5  	"strings"
     6  	"time"
     7  )
     8  
     9  type javaFmtGoLayout struct {
    10  	JavaRegex *regexp.Regexp
    11  	GoLayout  string
    12  }
    13  
    14  var timeFormatConvert = []javaFmtGoLayout{
    15  	{JavaRegex: regexp.MustCompile(`(?i)yyyy`), GoLayout: "2006"},
    16  	{JavaRegex: regexp.MustCompile(`(?i)yy`), GoLayout: "06"},
    17  	{JavaRegex: regexp.MustCompile(`MM`), GoLayout: "01"},
    18  	{JavaRegex: regexp.MustCompile(`(?i)dd`), GoLayout: "02"},
    19  	{JavaRegex: regexp.MustCompile(`(?i)hh`), GoLayout: "15"},
    20  	{JavaRegex: regexp.MustCompile(`mm`), GoLayout: "04"},
    21  	{JavaRegex: regexp.MustCompile(`(?i)sss`), GoLayout: "000"},
    22  	{JavaRegex: regexp.MustCompile(`(?i)ss`), GoLayout: "05"},
    23  }
    24  
    25  // FormatTime format time with Java style layout.
    26  func FormatTime(t time.Time, s string) string {
    27  	for _, f := range timeFormatConvert {
    28  		s = f.JavaRegex.ReplaceAllStringFunc(s, func(layout string) string {
    29  			return t.Format(f.GoLayout)
    30  		})
    31  	}
    32  
    33  	return s
    34  }
    35  
    36  // GlobName format time with Java style layout.
    37  func GlobName(s string) string {
    38  	for _, f := range timeFormatConvert {
    39  		s = f.JavaRegex.ReplaceAllStringFunc(s, func(layout string) string {
    40  			return strings.Repeat("?", len(layout))
    41  		})
    42  	}
    43  
    44  	return s
    45  }
    46  
    47  // ConvertFormat converts Java style layout to golang.
    48  func ConvertFormat(s string) string {
    49  	for _, f := range timeFormatConvert {
    50  		s = f.JavaRegex.ReplaceAllString(s, f.GoLayout)
    51  	}
    52  
    53  	return s
    54  }