-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmethods.go
48 lines (36 loc) · 915 Bytes
/
methods.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package main
import (
"time"
"fmt"
)
type Person struct {
userId int
username string
birthday int
}
func (user *Person) computeAge() int {
return user.computeAge2(time.Now())
}
func (user Person) computeAge2(currentTime time.Time) int {
birthday := time.Unix(int64(user.birthday), 0)
age := currentTime.Year() - birthday.Year()
switch {
case birthday.Month() < currentTime.Month():
age--
case birthday.Month() == currentTime.Month() && birthday.Day() < currentTime.Day():
age--
}
return age
}
func main() {
location, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
fmt.Println(err)
}
user := Person{userId: 100001, username: "Luckyboys", birthday: int(time.Date(1984, time.December, 8, 0, 0, 0, 0, location).Unix())}
fmt.Println(user)
fmt.Println(user.computeAge())
userPointer := &user
fmt.Println(userPointer)
fmt.Println(userPointer.computeAge2(time.Now()))
}