根据出生日期计算一个人的年龄、星座、生肖是平时常用的例子,下面是简单实现代码。
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"fmt"
"time"
)
func main() {
y, m, d := GetTimeFromStrDate("1988-08-18")
fmt.Println(GetAge(y), string('岁'))
fmt.Println(GetConstellation(m, d))
fmt.Println(GetZodiac(y))
}
func GetTimeFromStrDate(date string) (year, month, day int) {
const shortForm = "2006-01-02"
d, err := time.Parse(shortForm, date)
if err != nil {
fmt.Println("出生日期解析错误!")
return 0, 0, 0
}
year = d.Year()
month = int(d.Month())
day = d.Day()
return
}
func GetZodiac(year int) (zodiac string) {
if year <= 0 {
zodiac = "-1"
}
start := 1901
x := (start - year) % 12
if x < 0 {
x += 12
}
switch x {
case 1:
zodiac = "鼠"
case 0:
zodiac = "牛"
case 11:
zodiac = "虎"
case 10:
zodiac = "兔"
case 9:
zodiac = "龙"
case 8:
zodiac = "蛇"
case 7:
zodiac = "马"
case 6:
zodiac = "羊"
case 5:
zodiac = "猴"
case 4:
zodiac = "鸡"
case 3:
zodiac = "狗"
case 2:
zodiac = "猪"
}
return
}
func GetAge(year int) (age int) {
if year <= 0 {
age = -1
}
nowyear := time.Now().Year()
age = nowyear - year
return
}
func GetConstellation(month, day int) (star string) {
switch {
case month <= 0, month >= 13, day <= 0, day >= 32:
star = "-1"
case (month == 1 && day >= 20), (month == 2 && day <= 18):
star = "水瓶座"
case (month == 2 && day >= 19), (month == 3 && day <= 20):
star = "双鱼座"
case (month == 3 && day >= 21), (month == 4 && day <= 19):
star = "白羊座"
case (month == 4 && day >= 20), (month == 5 && day <= 20):
star = "金牛座"
case (month == 5 && day >= 21), (month == 6 && day <= 21):
star = "双子座"
case (month == 6 && day >= 22), (month == 7 && day <= 22):
star = "巨蟹座"
case (month == 7 && day >= 23), (month == 8 && day <= 22):
star = "狮子座"
case (month == 8 && day >= 23), (month == 9 && day <= 22):
star = "处女座"
case (month == 9 && day >= 23), (month == 10 && day <= 22):
star = "天秤座"
case (month == 10 && day >= 23), (month == 11 && day <= 21):
star = "天蝎座"
case (month == 11 && day >= 22), (month == 12 && day <= 21):
star = "射手座"
case (month == 12 && day >= 22), (month == 1 && day <= 19):
star = "魔蝎座"
}
return
}
运行输出:
1
2
3
27 岁
狮子座
龙
本文网址: https://golangnote.com/topic/34.html 转摘请注明来源