Golang笔记

GoLang 根据出生日期计算年龄、星座、生肖

根据出生日期计算一个人的年龄、星座、生肖是平时常用的例子,下面是简单实现代码。

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
}

运行输出:

27 岁
狮子座
龙
本文网址: https://golangnote.com/topic/34.html (转载注明出处)
关于GolangNote:记录在工作中使用golang 遇到、面临的相关问题及解决方法。如果你在这里获得一些知识或信息,解决你的编程问题,请考虑捐赠给不幸的人或者你喜欢的慈善机构,除捐赠外,种植树木、志愿服务或减少排碳的行为也很有益处。如果你有任何问题可以在下面 留言
Be the first to comment!
Captcha image