Go语言练习---判断闰年以及根据现在的秒数求现在的年月日

package main

import (
	"fmt"
	"math"
	"time"
)

/*
@闰年判断
·封装一个函数判断某一个年份是不是闰年(整4不整百,或者整四百)(例如:公元4年是如年,公元100、200、300不是闰年,公元400年是闰年)
·计算一年的精确天数
@根据当前时间纳秒求年月日
·time.Now().Unix()会返回距离1970年零时所逝去的时间秒数:1234567890
·据此求出今天的年月日(一年有60*24*365秒,整除得年;对一年的秒数求余,看看余数中有多少完整的60*24*30就有多少个月;)
·不许借助外部包,尤其是time包!
*/

func IsLeapYear(year int) bool {
	if (year%4 == 0 && year%100 != 0) || (year%400 == 0) ||(year%1000==0){
		return true
	}
	return false
}

var OrdinaryYearMonthDays = [12]int{31,28,31,30,31,30,31,31,30,31,30,32}
var LeapYearMonthDays = [12]int{31,29,31,30,31,30,31,31,30,31,30,32}

func GetDate(elapsedSeconds int)(year,month,day int) {

	//var year,month,day int

	for i := 1900; i <= 2000; i++ {
		if IsLeapYear(i) {
			fmt.Println(i, "是闰年")
		}
	}

	//一年的精确天数
	daysPerYear := (365*400 + (24*3 + 25)) / 400.0
	secondsPerDay := float64(24 * 3600)
	secondsPerYear := secondsPerDay * daysPerYear

	//计算今年是哪一年
	//elapsedSeconds := int(time.Now().Unix())
	elapsedYears := int(float64(elapsedSeconds) / secondsPerYear)
	year = 1970 + elapsedYears
	fmt.Println(year)

	//计算当前是几月
	//今年逝去的秒数:1970年后逝去的总秒数-今年以前的48个整年所包含的秒数
	thisYearSeconds := float64(elapsedSeconds) - float64(elapsedYears)*secondsPerYear
	//今年过去了多少天
	thisYearDays := int(math.Ceil(thisYearSeconds / secondsPerDay))
	fmt.Println(thisYearDays)

	var thisYearMonthDays [12]int
	if IsLeapYear(year){
		thisYearMonthDays = LeapYearMonthDays
	}else {
		thisYearMonthDays = OrdinaryYearMonthDays
	}

	var tempDays = 0
	for i, monthDays:=range thisYearMonthDays  {
		pastMonthDays := tempDays
		tempDays += monthDays
		fmt.Println(i,tempDays)
		if tempDays >= thisYearDays{
			month =i+1
			//今年过去的天数-过去11个整月的天数
			day = thisYearDays - pastMonthDays
			break
		}
	}
	fmt.Println("month=", month)
	fmt.Println("day=", day)
	return
}

func main() {
	//year, month, day := GetDate(int(time.Now().Unix()))
	//fmt.Printf("当前是%d年%d月%d日", year,month,day)
	pastSeconds := int(time.Date(2019, 11, 18, 22, 57, 1, 0, time.Local).Unix())
	year, month, day := GetDate(pastSeconds)
	fmt.Printf("当前是%d年%d月%d日\n", year,month,day)
	fmt.Println(pastSeconds,int(time.Now().Unix()))
}

  

猜你喜欢

转载自www.cnblogs.com/yunweiqiang/p/11886250.html