github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/helper/mmtime.go (about)

     1  package helper
     2  
     3  import (
     4  	"fmt"
     5  	"strconv"
     6  	"time"
     7  )
     8  
     9  // FMT_TYPE_NOMAL
    10  const (
    11  	DATE_TIME_FMT = "2006-01-02 15:04:05"
    12  
    13  	DATE_FMT = "2006-01-02"
    14  
    15  	TIME_FMT = "15:04:05"
    16  
    17  	DATE_TIME_FMT_CN = "2006年01月02日 15时04分05秒"
    18  
    19  	DATE_FMT_CN = "2006年01月02日"
    20  
    21  	TIME_FMT_CN = "15时04分05秒"
    22  )
    23  
    24  const SecondInNano = 1000 * 1000 * 1000
    25  
    26  //return 1441006057 in sec
    27  func GetTimestamp() int64 {
    28  	return time.Now().Unix()
    29  }
    30  
    31  //return 1441006057 in sec
    32  func GetTimestampString() string {
    33  	return strconv.FormatInt(GetTimestamp(), 10)
    34  }
    35  
    36  // return 1441007112776 in millisecond
    37  func GetTimestampInMilli() int64 {
    38  	return int64(time.Now().UnixNano() / (1000 * 1000)) // ms
    39  }
    40  
    41  // return 1441007112776 in millisecond
    42  func GetTimestampInMilliString() string {
    43  	return strconv.FormatInt(GetTimestampInMilli(), 10)
    44  }
    45  
    46  //微秒
    47  func GetTimestampInMicro() int64 {
    48  	return int64(time.Now().UnixNano() / 1000) // ms
    49  }
    50  
    51  // 微秒
    52  func GetTimestampInMicroString() string {
    53  	return strconv.FormatInt(GetTimestampInMicro(), 10)
    54  }
    55  
    56  //format
    57  func GetCurrentTimeFormat(format string) string {
    58  	return GetTimeFormat(GetTimestamp(), format)
    59  }
    60  
    61  //
    62  func GetTimeFormat(second int64, format string) string {
    63  	return time.Unix(second, 0).Format(format)
    64  }
    65  
    66  // Timing the cost of function call, unix nano was returned
    67  func Elapse(f func()) int64 {
    68  	now := time.Now().UnixNano()
    69  	f()
    70  	return time.Now().UnixNano() - now
    71  }
    72  
    73  // Timing the cost of function call, unix nano was returned
    74  func ElapseString(f func()) string {
    75  	return strconv.FormatInt(Elapse(f), 10)
    76  }
    77  
    78  // GetMonthDays return days of the month/year
    79  func GetMonthDays(year, month int) int {
    80  	switch month {
    81  	case 1, 3, 5, 7, 8, 10, 12:
    82  		return 31
    83  	case 4, 6, 9, 11:
    84  		return 30
    85  	case 2:
    86  		if IsLeapYear(year) {
    87  			return 29
    88  		}
    89  		return 28
    90  	default:
    91  		panic(fmt.Sprintf("Illegal month:%d", month))
    92  	}
    93  }
    94  
    95  // IsLeapYear check whether a year is leay
    96  func IsLeapYear(year int) bool {
    97  	if year%100 == 0 {
    98  		return year%400 == 0
    99  	}
   100  
   101  	return year%4 == 0
   102  }