PHP get time from personal identity number under 1970 - php

I have problem, I can't get time from personal identity number under 1970, I need to solve that, but using time. My function looks like. I don't know which way I can go. Thanks!
function getBirthDayFromRd($rd){
$day = substr($rd,4,2);
$month = substr($rd, 2,2);
$year = substr($rd, 0,2);
if($month>=51 and $month<=62){
$month = $month - 50;
}
$time = strtotime($day.".".$month.".".$year);
return date("d.m.Y", $time);
}

strtotime() fails due to its being tied to the Unix epoch which does not support dates prior to 1970. Just use DateTime which can handle pre-1970 dates and convert dates easily:
function getBirthDayFromRd($rd){
$date = DateTime::createFromFormat('ymd',$rd);
if($date->format('Y') > date("Y")) {
$date->modify('-100 years');
}
return $date->format('d.m.Y');
}
DateTime::createFromFormat() parses your date and creates the DateTime object. Then we just call DateTime::format() to format it in the desired format.
update
Just fixed a bug where pre-1970 dates were shown 100 years in the future.
Demo

I solve it another way, but u started me up.
if($year < 70){
$year = $year+1900;
$time = date_create_from_format("d.m.Y", $day.".".$month.".".$year);
return date_format($time, "d.m.Y");
}else{
$time = strtotime($day.".".$month.".".$year);
return date("d.m.Y", $time);
}

Related

date manipulation PHP

I need to create a date object that will be changed by parameters that i get.
If I'll get -7 for days it will take me a week ago.
Here is my code. How do I format the date correctly?
public function get_time_get($myear=0,$mmonth=0,$mday=0,$mhour=0,$mminute=0,$msecond=0){
$year=date('y') +$myear;
$month=date('m')+$mmonth;
$day = date('d')+$mday;
$hour= date('H'+$mhour); // there is a bug
$minute = date('i')+$mminute;
$seconds= date('s')+$msecond;
$date=mktime($year,$month,$day,$hour,$minute,$seconds);
$t =date("Y-m-d H:i:s", $date);
debug($date);
}
You can see that I try to get the time , but I get this:2021-11-30 17:08:29
That is not correct
You wrote:
$hour= date('H'+$mhour);
But it should be:
$hour = date('H') + $mhour;
The $mhour should be outside of the date function.

Create Date object in PHP for dates before 1970 in certain format

I have date witch is formatted d-m-y like 22-10-49 I want to convert it to Date object to save it in my mysql Database. I try :
DateTime::createFromFormat('d-m-y', $mydate , new DateTimeZone('GMT'));
but the result is 2049-10-22 instead of 1949-10-22. I searched and got that createFromFormat only returns date after 1970. but I don't know what to do.
P.s: 22-10-49 is what I have, and there are several other dates like this, I cannot change the format of it or convert it to 22-10-1949 or any other formats.
P.S 2 : "I'm working with birthdays and excpect 22-10-15 to be 1915 rather than 2015.
Try this function.
Edit: First we will convert two digit year in 4 digit. Then we will form complete date and pass it to function.
$original_date = '22-10-49';
$date_part = explode('-',$original_date);
$baseyear = 1900; // range is 1900-2062
$shortyear = $date_part[2];
$year = 100 + $baseyear + ($shortyear - $baseyear) % 100;
$subdate = substr( $original_date, 0, strrpos( $original_date, '-' ) );
$string = $subdate."-".$year;
echo safe_strtotime($string);
function safe_strtotime($string)
{
if(!preg_match("/\d{4}/", $string, $match)) return null; //year must be in YYYY form
$year = intval($match[0]);//converting the year to integer
if($year >= 1970) return date("Y-m-d", strtotime($string));//the year is after 1970 - no problems even for Windows
if(stristr(PHP_OS, "WIN") && !stristr(PHP_OS, "DARWIN")) //OS seems to be Windows, not Unix nor Mac
{
$diff = 1975 - $year;//calculating the difference between 1975 and the year
$new_year = $year + $diff;//year + diff = new_year will be for sure > 1970
$new_date = date("Y-m-d", strtotime(str_replace($year, $new_year, $string)));//replacing the year with the new_year, try strtotime, rendering the date
return str_replace($new_year, $year, $new_date);//returning the date with the correct year
}
return date("Y-m-d", strtotime($string));//do normal strtotime
}
Output: 1949-10-22
Source: Using strtotime for dates before 1970

PHP date compare older than 15 days

i am struggling for a long time to set a specific date but i am not getting correct out put.
i want to get date from user and compare that date with the date 15 days older then today. if it is older than 15 days then convert to today else print what it is.
$todaydate= $_GET['date'];// getting date as 201013 ddmmyy submitted by user
$todaydate=preg_replace("/[^0-9,.]/", "", $todaydate);
$today =date("dmy"); //today ddmmyy
$older= date("dmy",strtotime("-15 day")); // before 15 days 051013
if ($todaydate <= $older){
$todaydate= $today;}
problem is, it is taking date as number and giving wrong result.
Comparing date strings is a bit hacky and prone to failure. Try comparing actual date objects
$userDate = DateTime::createFromFormat('dmy', $_GET['date']);
if ($userDate === false) {
throw new InvalidArgumentException('Invalid date string');
}
$cmp = new DateTime('15 days ago');
if ($userDate <= $cmp) {
$userDate = new DateTime();
}
Also, strtotime has some severe limitations (see http://php.net/manual/function.strtotime.php#refsect1-function.strtotime-notesand) and is not useful in non-US locales. The DateTime class is much more flexible and up-to-date.
try this one:
<?php
$todaydate = date(d-m-Y,strtotime($_GET['date']));
$today = date("d-m-Y");
$older= date("d-m-Y",strtotime("-15 day"));
if (strtotime($todaydate) <= strtotime($older))
{
$todaydate= $today;
}
?>
$previousDate = "2012-09-30";
if (strtotime($previousDate) <= strtotime("-15 days")) {
//the date in $previousDate is earlier or is equal to the date 15 days before from today
}

Easier way for PHP date calculations?

I'm trying to determine when a user has last logged on. My current method works but is there an easier way of determining this so that I could determine last X hours etc?
This is what I currently use:
$last_login_di = getdate($last_login);
$now = time();
$now_di = getdate($now);
$today = mktime(0,0,0,$now_di['mon'],$now_di['mday'], $now_di['year']);
if ($last_login > $today) {
return 'Online Today';
}
$yesterday = $now-86400;
$yesterday_di = getdate($yesterday);
$yesterday = mktime(0,0,0,$yesterday_di['mon'],$yesterday_di['mday'], $yesterday_di['year']);
if ($last_login > $yesterday) {
return 'Online Yesterday';
}
if (($now - $last_login < 604800) ) {
return 'Online This Week';
}
....
Try strtotime() (see relative formats it accepts) or better yet, the DateTime, DateInterval classes.
For example, the $yesterday variable creation is prone errors near datetime savings. strtotime() handles this properly with:
$yesterday = strtotime('-1 day');
While the $last_login check can be written like:
if (strtotime('-1 week') < $last_login) {
// ...
}
If you need to support different timezones you probably better of with the DateTime objects though.
Have a look at the DateTime and related classes DateTime Book on php.net. The DateInterval class may be of particular use to you.
How do you get the date? Using MySQL? Use UNIX_TIMESTAMP for dates, eg SELECT UNIX_TIMESTAMP(last_login) AS last_login_timestamp FROM ... Then you can better calculate in PHP (using date_diff)
I think your code's fine. But the $yesterday var is wrong.
It should be:
$yesterday = $today - 86400;
In your code $yesterday means $a_day_ago.
The same for the last week.
You should heavily use the date objects built-in with PHP.
$now = new DateTime();
$yesterday = new DateTime('yesterday');
$lastWeek = new DateTime('last week');
Now you are able to to any comparison logic you want, using the basic comparison operators:
if ($last_login > $now) {
...
} else if ($last_login > $yesterday) {
...
} else if ($last_login > $lastWeek) {
...
} else {
...
}
If you choose not to use the objects, try to avoid the time() function. That makes unit testing impossible. Tests should never depend on environment.
Use $_SERVER['REQUEST_TIME'] instead so you can mock it later.

PHP date calculation

What is the best (date format independent way) in PHP to calculate difference in days between two dates in specified format.
I tried the following function:
function get_date_offset($start_date, $end_date)
{
$start_time = strtotime($start_date);
$end_time = strtotime($end_date);
return round(($end_time-$start_time)/(3600*24));
}
It works ok on linux box, but when running under windows strtotime returns ''.
EDIT:
Input date is in mm/dd/yyyy format, but I would like to make it accept $format as a parameter.
I need only difference in days.
If you do not want or you cannot use Zend Framework or Pear package try this function i hope this would help:
function dateDifference($date1, $date2)
{
$d1 = (is_string($date1) ? strtotime($date1) : $date1);
$d2 = (is_string($date2) ? strtotime($date2) : $date2);
$diff_secs = abs($d1 - $d2);
$base_year = min(date("Y", $d1), date("Y", $d2));
$diff = mktime(0, 0, $diff_secs, 1, 1, $base_year);
return array
(
"years" => abs(substr(date('Ymd', $d1) - date('Ymd', $d2), 0, -4)),
"months_total" => (date("Y", $diff) - $base_year) * 12 + date("n", $diff) - 1,
"months" => date("n", $diff) - 1,
"days_total" => floor($diff_secs / (3600 * 24)),
"days" => date("j", $diff) - 1,
"hours_total" => floor($diff_secs / 3600),
"hours" => date("G", $diff),
"minutes_total" => floor($diff_secs / 60),
"minutes" => (int) date("i", $diff),
"seconds_total" => $diff_secs,
"seconds" => (int) date("s", $diff)
);
}
The PEAR Date class offers all kinds of features for finding the differences between dates and about 1000 other things as well. The docs for it are here...
The problem with PHP is that it doesn't have a definite DateTime type. You can use a Unix timestamp, or the built-in DateTime class, but they are pretty limited in their functionality. I expect that there should be some 3rd party classes with more extensive support for date-time calculations, but I haven't looked for it.
Using Unix timestamps for date (not time) calculations is also tricky. You'd have to discard the time part, but simply resetting to 00:00 is not safe because of daylight savings time (DST). DST has the effect that there are two days every year that don't have exactly 24 hours. Thus, when adding/subtracting dates you might end up with a value that does not divide evenly with 3600*24.
I'd suggest looking for some 3rd party class that has proper support for all this stuff. Date/Time calculations are awesome in their ugliness. :P
The Zend Framework has the class Zend_Date for dealing with "date math". It works around system specific timestamp limits by using the BCMath extension, or if that's not available limits the timestamps by max float value for your system.
// example printing difference in days
require('Zend/Date.php');
$date1 = new Zend_Date();
$date1->set(2, Zend_Date::MONTH);
$date1->set(27, Zend_Date::DAY);
$date1->set(2008, Zend_Date::YEAR);
$date2 = new Zend_Date();
$date2->set(3, Zend_Date::MONTH);
$date2->set(3, Zend_Date::DAY);
$date2->set(2008, Zend_Date::YEAR);
echo ($date2->getTimestamp() - $date1->getTimestamp()) / (3600*24);
I'm not sure what is considered best, since there is no built-in function in PHP for doing this, but some people have used gregoriantojd(), for example in this forum post.
gregoriantojd() gives the same results as using strtotime(), see this blogpost for how to do it:
http://www.phpro.org/examples/Calculate-Age-With-PHP.html
The following works for me. Believe I found it on the php.net docs somewhere.
*Edit - Woops, didn't see csl's post. This is the exact function from his link, must have been where I found it. ;)
//Find the difference between two dates
function dateDiff($startDate, $endDate)
{
// Parse dates for conversion
$startArry = date_parse($startDate);
$endArry = date_parse($endDate);
// Convert dates to Julian Days
$start_date = gregoriantojd($startArry["month"], $startArry["day"], $startArry["year"]);
$end_date = gregoriantojd($endArry["month"], $endArry["day"], $endArry["year"]);
// Return difference
return round(($end_date - $start_date), 0);
}
I was trying to calculate the difference of two dates for the purpose of showing the duration of an event. Most of the functions given on the problem fails if the event has a duration form friday at 17:00 to sunday at 15:00. My goal was to find the difference between the dates like:
date('Ymd',$end)-date('Tmd',$begining);
But that is likly to fail because there isn't 99 month in a year and 99 days in a month. I could convert the date string to UNIX timestamp and divide by 60*60*12, but some days have a greater or lesser number of hours, sometimes there's eaven a leap secound. So I made my own function using getdate() a function that returns an array of innformation about the timestamp.
/*
* datediff($first,$last)
* $first - unix timestamp or string aksepted by strtotime()
* $last - unix timestamp or string aksepted by strtotime()
*
* return - the difference in days betveen the two dates
*/
function datediff($first,$last){
$first = is_numeric($first) ? $first : strtotime($first);
$last = is_numeric($last ) ? $last : strtotime($last );
if ($last<$first){
// Can't calculate negative difference in dates
return -1;
}
$first = getdate($first);
$last = getdate($last );
// find the difference in days since the start of the year
$datediff = $last['yday'] - $first['yday'];
// if the years do not match add the appropriate number of days.
$yearCountedFrom = $first['year'];
while($last['year'] != $yearCountedFrom ){
// Take leap years into account
if( $yearCountedFrom % 4 == 0 && $yearCountedFrom != 1900 && $yearCountedFrom != 2100 ){
//leap year
$datediff += 366;
}else{
$datediff += 365;
}
$yearCountedFrom++;
}
return $datediff;
}
Concerning the GregorianToJD() function, it might work, but I feel a little bit uneasy since I do not understand how it work.
Let's not overengineer, guys.
$d1 = strtotime($first_date);
$d2 = strtotime($second_date);
$delta = $d2 - $d1;
$num_days = ($delta / 86400);
Calculate the difference between two Dates (and time) using Php. The following page provides a range of different methods (7 in total) for performing date / time calculations using Php, to determine the difference in time (hours, munites), days, months or years between two dates.
See Php Date Time - 7 Methods to Calculate the Difference between 2 dates
PHP 5.2 introduces the DateTime and DateInterval classes which makes this easy:
function get_date_offset($start_date, $end_date)
{
$start_time = new DateTime($start_date);
$end_time = new DateTime($end_date);
$interval = $end_time->diff($start_time);
return $interval->format('%a days');
}

Categories