秒到年 [英] Seconds to Year

查看:36
本文介绍了秒到年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我正在尝试重新创建 PHP 日期的年份功能.使用自 1970 年 1 月 1 日以来的秒数,我试图在不使用内置函数的情况下获得年份.我有一个想法,但由于闰年它没有奏效.谁能给我一个工作公式,从 1970 年开始用几秒钟,然后从中得到一年?

Basically, I am trying to recreate PHP date's year functionality. Using the number of seconds since 1 January 1970, I am trying to get the year with out using a built in function. I had a an idea, but it did not work because of leap years. Can anyone give me a working formula that takes the seconds since 1970 and gets a year from it?

推荐答案

找到你需要处理飞跃的年份.

To find the year you need to deal with leaps.

从 1 开始的年份被排序为 4 年的块,其中最后一个多一天,对吗?所以你有块:

The years from 1 are ordered as blocks of 4 years been the last of them one day longer, right? So you have blocks of:

seconds_block = 365*3 + 366 days = 126230400 seconds
seconds_year = 365 days = 31536000 seconds

1970 年是其区块的第二年,因此:

1970 is the second year of its block so with this:

<?php 
//test_year.php   
$given_seconds = $argv[1];

$seconds_year = 31536000;
$seconds_block = 126230400;
$total_blocks_to_1968 = 492;
$actual_block = floor((($given_seconds + $seconds_year) / $seconds_block)) + $total_blocks_to_1968;
$actual_offset_from_last_block = ($given_seconds + $seconds_year) % $seconds_block;
$actual_year_of_the_block = min(floor($actual_offset_from_last_block / $seconds_year) + 1, 4);
$actual_year = $actual_block * 4 + $actual_year_of_the_block;
echo $actual_year;

正在测试...

$ php test_year.php 0
1970
$ php test_year.php 1
1970
$ php test_year.php -1
1969
$ php test_year.php 31536000
1971
$ php test_year.php 31535999
1970
$ php test_year.php 126230400
1974
$ php test_year.php 126230399
1973

更多:除了能被 100 整除(但不能被 400 整除)之外,如果能被 4 整除,则一年是闰年.

More: One year is leap if is divisible by 4 except those divisible by 100 (but not by 400).

function isLeap(year){
    return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)
}

伪代码公式

x = input // number of seconds since 1970

sy = 31536000  // seconds a non leap year
sb = 126230400  // seconds a block of 3 non leap years and one that is

actual_year = (floor(((x + sy) / sb)) + 492) * 4 + 
              (min(floor(((x + sy) % sb) / sy) + 1, 4));

干杯

这篇关于秒到年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆