473,804 Members | 2,257 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

i write a date calculator, but there always get a one-day-distance wrong

<?php
/**
* check ine year is a leap year, and return the month day array
*
* @param int $year **the year must bigger than zero**
* @return array
*/
function is_leap_year($y ear){
$year=floor($ye ar);
if ($year<=0) {
return false;
}
$flag = false;//leap year flag

/*
* check the year
*/
if ($year%100==0) {
if ($year%400==0) {
$flag = true;
}
}
else {
if ($year%4==0) {
$flag = true;
}
}
$mon[0] = $flag;//leap year flag
$mon[1] = 31;
$mon[2] = $flag?29:28;
$mon[3] = 31;
$mon[4] = 30;
$mon[5] = 31;
$mon[6] = 30;
$mon[7] = 31;
$mon[8] = 31;
$mon[9] = 30;
$mon[10] = 31;
$mon[11] = 30;
$mon[12] = 31;
return $mon;
}

/**
* read a datetime string and explode it in to an array
* string format: YY-M-D h:m:s
*
* @param string $datetime
* @return array
*/
function get_date_time($ datetime){
$current = explode(' ', $datetime);
$date = $current[0];
$time = $current[1];
$date_tmp = explode('-',$date);
$time_tmp = explode(':',$ti me);
$current['year'] = $date_tmp[0]+0;
$current['month'] = $date_tmp[1]+0;
$current['day'] = $date_tmp[2]+0;
$current['hour'] = $time_tmp[0]+0;
$current['minute'] = $time_tmp[1]+0;
$current['second'] = $time_tmp[2]+0;
return $current;
}

/**
* calculate the datetime
*
*
* @param string $datetime //string format: YY-M-D h:m:s
* @param array $diff //time stamp
* array('year'=>i nt, 'month'=>int, 'day'=>int,
* 'hour'=>int, 'minute'=>int,' second'=>int)
* @return string //result string format: YYYY-MM-DD
hh:mm:ss
*/
function date_diff($date time, $diff){
$current = get_date_time($ datetime); //get the init time stamp
if($curent['year']<1){
return false;
}
$mon = is_leap_year($c urrent['year']); // get the current month
days

/*
* init
*/
$second_tmp = $current['second']+$diff['second'];
$minute_tmp = $current['minute']+$diff['minute'];
$hour_tmp = $current['hour']+$diff['hour'];
$year_tmp = $current['year']+$diff['year'];
$month_tmp = $current['month']+$diff['month'];
$day_tmp=$curre nt['day']+$diff['day'];

/*
* convert the TIME stamp into seconds
*/
$hour_tmp = $hour_tmp*60*60 ;
$minute_tmp = $minute_tmp*60;
$second_tmp = $hour_tmp+$minu te_tmp+$second_ tmp;
//convert the seconds into (day + second), the second couldn't be
negative
if ($second_tmp<0) {
$day = intval($second_ tmp/(24*60*60))-1;
}
else {
$day = intval($second_ tmp/(24*60*60));
}
$day_tmp=$curre nt['day']+$diff['day']+$day;
$second_tmp = $second_tmp-($day*24*60*60) ;

/*
* convert the seconds into h:m:s
*/
$hour_tmp = intval($second_ tmp/(60*60));
$second_tmp = $second_tmp-($hour_tmp*60*6 0);
$minute_tmp = intval($second_ tmp/(60));
$second_tmp = $second_tmp-($minute_tmp*60 );

/*
* month caculate
*/
if ($month_tmp<0) {
while ($month_tmp<1) {
$year_tmp--;
$month_tmp+=12;
}
}
else {
while ($month_tmp>12) {
$year_tmp++;
$month_tmp-=12;
}
}

/*
* day caculate
*/
if ($day_tmp<0) {
while ($day_tmp<1) {
$month_tmp--;
if ($month_tmp<1) {
$year_tmp--;
$month_tmp=12;
$mon = is_leap_year($y ear_tmp);
}
$day_tmp+=$mon[$month_tmp];
}
}
else {
while ($day_tmp>$mon[$month_tmp]){
$day_tmp-=$mon[$month_tmp];
$month_tmp++;
if ($month_tmp>12) {
$year_tmp++;
$month_tmp=1;
$mon = is_leap_year($y ear_tmp);
}
}
}
if ($year_tmp<=0) { return false; }
if ($month_tmp<10) { $month_tmp='0'. $month_tmp; }
if ($day_tmp<10) { $day_tmp='0'.$d ay_tmp; }
if ($hour_tmp<10) { $hour_tmp='0'.$ hour_tmp; }
if ($minute_tmp<10 ){ $minute_tmp='0' .$minute_tmp; }
if ($second_tmp<10 ){ $second_tmp='0' .$second_tmp; }
$str_date = $year_tmp.'-'.$month_tmp.'-'.$day_tmp.'
'.$hour_tmp.':' .$minute_tmp.': '.$second_tmp;
return $str_date;
}

/**
* Run date_diff()
**/
$diff['year'] = -10;
$diff['month'] = -100;
$diff['day'] = -500;
$diff['hour'] = -98;
$diff['minute'] = -237;
$diff['second'] = -999;
echo date_diff('2000-1-1 0:0:0',$diff)." \n";
echo date("Y-m-d H:i:s",mktime(0-98, 00-237, 0-999, 1-100, 1-500,
2000-10))."\n";
echo "\n";

$diff['year'] = 0;
$diff['month'] = 0;
$diff['day'] = -500;
$diff['hour'] = -98;
$diff['minute'] = 0;
$diff['second'] = 0;
echo date_diff('2000-1-1 0:0:0',$diff)." \n";
echo date("Y-m-d H:i:s",mktime(0-98, 00-0, 0-0, 1-0, 1-500,
2000-0))."\n";
?>

the result
=============== =============== ===========
1980-04-15 17:46:21
1980-04-14 17:46:21

1998-08-14 22:00:00
1998-08-14 22:00:00

please tell me what's wrong,
thanks!

Gucci Koo

Aug 26 '06 #1
7 1683
Zebrawszy my?li Gucci <ju******@gmail .comwyklepa?:

/**
* check ine year is a leap year, and return the month day array
*
* @param int $year **the year must bigger than zero**
* @return array
*/

OMG man, you should to rewrite this code...

1. try to use date("L") for leap year
2. too much of code
3. same solution for other functions....

--
~~~~~~~~~~~~~~~ ~~~~~~~~~~
..::[ ikciu ]::.
gg: 718845
www: e-irsa.pl
Aug 26 '06 #2
This is usually because there is the North American Daylight Savings time
built in to PHP.

Why write one yourself when there are loads already written?
Aug 26 '06 #3
has i have to calculate the datetime which beyond the unixtime on
32-bit server

Aug 26 '06 #4
Gucci wrote:
<?php
/**
* check ine year is a leap year, and return the month day array
*
* @param int $year **the year must bigger than zero**
* @return array
*/
function is_leap_year($y ear){
$year=floor($ye ar);
if ($year<=0) {
return false;
}
$flag = false;//leap year flag

/*
* check the year
*/
if ($year%100==0) {
if ($year%400==0) {
$flag = true;
}
}
else {
if ($year%4==0) {
$flag = true;
}
}
$mon[0] = $flag;//leap year flag
$mon[1] = 31;
$mon[2] = $flag?29:28;
$mon[3] = 31;
$mon[4] = 30;
$mon[5] = 31;
$mon[6] = 30;
$mon[7] = 31;
$mon[8] = 31;
$mon[9] = 30;
$mon[10] = 31;
$mon[11] = 30;
$mon[12] = 31;
return $mon;
}
<snip>

FWIW, this is one of many reasons why everyone should read K&R.

--
<?php echo 'Just another PHP saint'; ?>
Email: rrjanbiah-at-Y!com Blog: http://rajeshanbiah.blogspot.com/

Aug 26 '06 #5
i solve the problem

<?php
function get_date_time($ datetime){
if (!$datetime) {
return false;
}
$current = explode(' ', $datetime);
$date = $current[0];
$time = $current[1];
$date_tmp = explode('-',$date);
$time_tmp = explode(':',$ti me);
$current['year'] = $date_tmp[0]+0;
$current['month'] = $date_tmp[1]+0;
$current['day'] = $date_tmp[2]+0;
$current['hour'] = $time_tmp[0]+0;
$current['minute'] = $time_tmp[1]+0;
$current['second'] = $time_tmp[2]+0;
return $current;
}

function get_time_stamp( $stamp_array){
if (!$stamp_array) {
return false;
}
$diff['year'] = $stamp_array[0];
$diff['month'] = $stamp_array[1];
$diff['day'] = $stamp_array[2];
$diff['hour'] = $stamp_array[3];
$diff['minute'] = $stamp_array[4];
$diff['second'] = $stamp_array[5];
return $diff;
}

function is_leap_year($y ear){
$year=floor($ye ar);
if ($year<=0) {
return false;
}
$flag = false;

if ($year%100==0) {
if ($year%400==0) {$flag = true;}
}
else {
if ($year%4==0) {$flag = true;}
}
$mon = array($flag,31, ($flag?29:28),3 1,30,31,30,31,3 1,30,31,30,31);
return $mon;
}

function date_calc($stam p,&$litter,&$bi gger){
$time_name=arra y('second','min ute','hour','da y','month','yea r');
$time_base=arra y(60,60,24,null ,12,null);
$position = array_search($s tamp,$time_name );

$bigger_tmp = intval($litter/$time_base[$position]);
if ($bigger_tmp<0) {
$bigger_tmp--;
}
$litter = $litter-$bigger_tmp*$ti me_base[$position];
$bigger+=$bigge r_tmp;
}

function date_diff($star t,$diff_stamp){
$current = get_date_time($ start);
$diff = get_time_stamp( $diff_stamp);

/*
* IMPORTANT!!!
* MAKE ALL TIMESTAMP START AT ZERO
*/
$current['year']--;
$current['month']--;
$current['day']--;

$year = $current['year']+$diff['year'];
$month = $current['month']+$diff['month'];
$day = $current['day']+$diff['day'];
$hour = $current['hour']+$diff['hour'];
$minute = $current['minute']+$diff['minute'];
$second = $current['second']+$diff['second'];

date_calc('seco nd',$second,$mi nute);
date_calc('minu te',$minute,$ho ur);
date_calc('hour ',$hour,$day);
date_calc('mont h',$month,$year );

$year++;
$month++;
$day++;

$mon = is_leap_year($y ear);
if ($day<0) {
while ($day<1) {
$month--;
if ($month<1) {
$year--;
$month=12;
$mon = is_leap_year($y ear);
}
$day+=$mon[$month];
}
}
else {
while ($day>$mon[$month]){
$day-=$mon[$month];
$month++;
if ($month>12){
$year++;
$month=1;
$mon = is_leap_year($y ear);
}
}
}

if ($month<10) {$month='0'.$mo nth;}
if ($day<10) {$day='0'.$day; }
if ($hour<10) {$hour='0'.$hou r;}
if ($minute<10) {$minute='0'.$m inute;}
if ($second<10) {$second='0'.$s econd;}
return "$year-$month-$day $hour:$minute:$ second";
}
?>

Aug 27 '06 #6
On Sun, 27 Aug 2006 06:36:09 -0700, Gucci wrote:
if ($year%100==0) {
if ($year%400==0) {$flag = true;}
Are you *sure* this logic is correct? I'm not... and if it is, why bother
with the check for 100 years?

Aug 28 '06 #7
Steve wrote:
On Sun, 27 Aug 2006 06:36:09 -0700, Gucci wrote:

> if ($year%100==0) {
if ($year%400==0) {$flag = true;}


Are you *sure* this logic is correct? I'm not... and if it is, why bother
with the check for 100 years?
Yes, that is correct.

It is a leap year if the year is divisible by 400, or if its divisible
by 4 and not by 100.

He needs the $year % 100 for the else clause.
--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attgl obal.net
=============== ===
Aug 28 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
1649
by: Dennis M. Marks | last post by:
I've been updating by date stuff at my web site using much of the information obtained here. Would you please check it for any errors. The two pages are "Yearly Calendar" and "Date Calculator". There is no year validation on the "Yearly Calendar" but it is only correct for years 1 and up. There is full validation in the "Date Calculator" but I limited the dates to years 1-9999. I did not allow years before the year 1 since I am still...
4
1935
by: mwh | last post by:
Hi. If you remember, I posted Expressons Help. Now I am making a calculator with javascript. I can't get this to work: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <title>Calculator</title> <script language="Javascript"> <!-- Begin Hiding var total = 0
3
5219
by: Paul | last post by:
I want to make a simple calculator program but dont know where to get started. This is not GUI but a simple terminal program. It would get input like this Enter number: 5 + 10
5
6869
by: Steven Smith | last post by:
I was flicking through the windows accesories programs for some inspiration for todays vb challenge when I came accross the calculator program & thought that looks easy I could do that. However it hasn't turned out to be as easy as I first anticipated due to a calculators strange logic I done a bit of research on the web to see what I could come up with and I found this following page which outlines the ideas behind a calculator...
24
6348
by: firstcustomer | last post by:
Hi, Firstly, I know NOTHING about Javascript I'm afraid, so I'm hoping that someone will be able to point me to a ready-made solution to my problem! A friend of mine (honest!) is wanting to have on his site, a Javascript Calculator for working out the cost of what they want, for example: 1 widget and 2 widglets = £5.00
1
1760
by: teddymeu | last post by:
Hi Guys Dont have much experience in writing my own JavaScripts and have a problem to overcome for work They need a date calculator which displays 90 days forward from a selected date, it will always be 90 days. Can anyone advise if there is a script out there that already does this and where to find it, or give me some help on coming up with something Kind Regards
25
5965
by: mereba | last post by:
Hello My country Ghana is changing its currency. I want to write a small programme in C++ that can covert from the old currency into the new one. I would like this programme to run behind a simple calculator- looking interface. I'm quite new to C++, and I would need some help. Please any suggestion is welcome :) The following is what I have been able to do so far:
3
11862
by: itsmichelle | last post by:
This is a very primative code of a java swing calculator. I have assigned all the number buttons and the operator buttons and I can add, subtract, multiply, and divide two numbers together. However, my teacher wants the operators to follow the algebraic order of operations by chaining multiple operations. Such as, 7 + 4 * 2= 15. The operatorListener is the ActionListener for the operator buttons. Thanks for any help you can give me. ...
3
2898
by: mandy335 | last post by:
public class Calculator { private long input = 0; // current input private long result = 0; // last input/result private String lastOperator = ""; // keeps track of the last operator entered /* Digit entered as integer value i * Updates the value of input accordingly to (input * 10) + i */
1
2565
by: chean | last post by:
Write a program that creates a simple calculator . The user enters two numbers in the text fields, Number 1 and Number 2. There are 4 buttons, labeled with “Add”, “Substract”, “Multiply” and “Divide”. When the user clicks any one buttons, the result of the operations to the two integers will be displayed in the Result text field. The program handles two kinds of exceptions: • NumberFormatException if Number 1 or Number 2 were not an integer...
0
9714
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9594
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10599
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9173
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7635
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6863
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5531
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4308
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.