简体   繁体   English

如何使用php计算进入我年龄的年份

[英]How to calculate year from entering my age using php

How can i calculate year from entering my age using php. 如何使用php计算进入我年龄的年份。

example: 例:

i am entering my age as 24. 我进入24岁。

So that i need to get the year as 1985. 所以我需要把这一年当作1985年。

how this can be done. 如何做到这一点。

thanks in advance 提前致谢

If you knew simple math, you'd know that 2010 - 24 - 1 = 1985 or $year = date("Y") - $theirage - 1 ... But just giving an age does not accurately deduce what year they were born. 如果你知道简单的数学,你会知道2010 - 24 - 1 = 1985$year = date("Y") - $theirage - 1 ...但是只是给出一个年龄并不能准确推断出他们出生的那一年。 For example: 例如:

If the date is December 30, 2010 and they say they're 24, you're still saying they were born in 1985 when chances are very, very high that they were actually born in 1986. You cannot rely on their age to give you their birth year. 如果日期是2010年12月30日并且他们说他们是24岁,你仍然说他们出生于1985年,那时他们实际上是1986年出生的机会非常非常高。你不能依靠他们的年龄来给你他们的出生年份。

EDIT If that wasn't very clear: 编辑如果不是很清楚:

Today's date is June 16, 2010. So to be 24 years old, I would have needed to be born somewhere between June 17, 1985 and June 16, 1986. That's near half of the birthyears that would be 1985 and near half that would be 1986, causing a very high inaccuracy. 今天的日期是2010年6月16日。所以到了24岁,我需要在1985年6月17日到1986年6月16日之间的某个地方出生。那将是1985年的近一半的出生年,接近一半的出生年份。 1986年,造成非常高的不准确性。

To obtain the date 24 years ago, you can use strtotime : 要获得24年前的日期,您可以使用strtotime

$date = strtotime("-24 year");
echo date('%c', $date);

With DateTime : 使用DateTime

PHP > 5.2 PHP> 5.2

<?php
       function getBirthYear($age) {
               $now = new DateTime();
               $now->modify("-" . $age . " years");
               return $now->format("Y");
       }

       echo getBirthYear(24);
?>

PHP > 5.3 PHP> 5.3

<?php
       function getBirthYear($age) {
               $now = new DateTime();
               $now->sub(new DateInterval("P" . $age . "Y"));
               return $now->format("Y");
       }

       echo getBirthYear(24);
?>

Since you cannot give an exact year, it is better to specify a date range. 由于您无法给出确切的年份,因此最好指定日期范围。

If you are 24 years old today (we usually round down , not round off ), you were born between 17 Jun 1985 and 16 Jun 1986. 如果你是24岁今天(我们通常四舍五入 ,不四舍五入 ),在你出生1985年6月17日和1986年16月之间。

Methods of adding and subtracting dates have already been posted on this page. 添加和减去日期的方法已在此页面上发布。

I use a simple php script that I have made by myself: My_Age_Php 我使用了一个我自己制作的简单的PHP脚本: My_Age_Php

PHP 5.3.0还引入了date_diff函数作为DateTime类的一部分。

WARNING: This is inacurate but its a try. 警告:这是不可避免的,但它是一个尝试。

$yearBorn = round((((time()-($age*31556926))/31556926)+70));
$yearBorn = ($yearBorn>100)? "20".substr($yearBorn,1,2):"19".$yearBorn;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM