Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

How to calculate The difference between two dates format(Years,Months,days) you have a choice of the language?

example between '01/01/2000' and '10/08/2014' we have14 years07 months09 days

user-image
Question added by Deleted user
Date Posted: 2014/08/10
Tomasz Modrzejewski
by Tomasz Modrzejewski , Programmer , Company Skraw-Mech

Timing amount of time to a specific date Scripts PHP, mySQL The exact time to a specific date Often we want to make our page showed in great detail the time to a specific date - for example: end of the promotion date of birth solar eclipse ... Thanks to this article you will be able to see your own text with the exact time remaining for you to important events. The on-screen text will be included number years months days hours minutes seconds the rest of the event. How to use this article? Article: At the beginning describes a function in PHP that returns a text (string) describing the time remaining until a certain date. This feature can copy and paste into your own program and use freely. Shows how to use the function described. At the end of this document for a complete, sample web page with PHP code metering the exact time to the end of a fictitious promotion. This website uses previously written function. You can paste this page into your site, test, modify, adapt to their needs. Description of functions ZwrocStringOpisujacyCzasDoWydarzenia What does the ZwrocStringOpisujacyCzasDoWydarzenia The key feature of our program is PHP ZwrocStringOpisujacyCzasDoWydarzenia declared as follows:   ZwrocStringOpisujacyCzasDoWydarzenia function ($ data_wydarzenia) {  }  Its argument is a string (text) contains the date of the event ($ data_wydarzenia) format as follows:        'Year-Month-Day Hour: Minute: Second' For example, $ data_wydarzenia can be either:        ' 2:36:29 p.m.' which means 17 June2030 roku 36 hours 14 minutes and29 seconds. ZwrocStringOpisujacyCzasDoWydarzenia function returns a text (string) describing the time remaining until the events contained in the variable $ data_wydarzenia for example:        years: 18 months: 11 days 2 hours: 6 minutes: 41 seconds: 26 which means that the date contained in the variable $ data_wydarzenia remained 18 years,11 months, 2 days,6 hours, 41 minutes and26 seconds. Date of current To calculate the difference between the current date and the date contained in the variable $ data_wydarzenia need to get the current date in the same format as the date contained in the variable $ data_wydarzenia. PHP function date Date allows you to download in any format. That's why we call Date as follows:   $ data_aktualna = Date ('Y-m-d H: i: s');  This means that: Year, month and day are separated by dashes (-) Year will be displayed in the form of4 characters (Y) Month will be displayed in the form of two characters (m) The day will be displayed in the form of two characters (d) After a space will be displayed at the 2 characters in24 hour format (H) After the colon will show minutes as 2 characters (and) After the colon will appear second as 2 characters (s) Everything is good, but we need not two dates and the difference in hours between two dates. Number of seconds since January1,1970 PHP function strtotime calculates how many seconds have passed since January1,1970. The name of this function, you can expand on Page To Time or Replace String On Time. In this way we change the date to the number of seconds that have elapsed between the given date and January1,1970. So now we create two variables that calculate how many seconds have elapsed since January1,1970 for both our dates:   $ liczba_sekund_dla_wydarzenia = strtotime ($ data_wydarzenia);   $ liczba_sekund_dla_aktualnej_daty = strtotime ($ data_aktualna);  What if the date of the event has already passed? We can now calculate how many seconds divides the current date and event ($ liczba_sekund_miedzy_datami):   $ liczba_sekund_miedzy_datami =         $ liczba_sekund_dla_wydarzenia - $ liczba_sekund_dla_aktualnej_daty;   if ($ liczba_sekund_miedzy_datami <= 0)      return "";  If the difference in seconds between the difference is negative it means that the time has passed and events turn an empty string (empty string) as well as exit our function. The difference of years between dates We have a number of seconds between dates (variable $ liczba_sekund_miedzy_datami). However, we are interested in at the beginning of the number of years between the dates. Note that the number of seconds in a year is:     iczba_dni_w_roku * liczb_godzin_w_dniu * liczba_minut_w_godzinie * liczba_sekund_w minutes or     365 *24 * 60 * 60 This value will not count (why bother when we have computers!) Just remember in $ liczba_sekund_w_roku. We note here a weakness of our program. Does not account for leap years have 366 days in May. Now just divide $ liczba_sekund_miedzy_datami by $ liczba_sekund_w_roku to have the number of years between the dates (remember the $ liczba_lat). Get a fraction. If the events left half of the year (0.5) is obviously a 0 full years remaining to the event. Therefore, the resulting number of years we round down using PHP fukcji Floor. Full code executing these tasks are listed below:   $ liczba_sekund_w_roku =365 *24 * 60 * 60;   $ liczba_lat = Floor ($ liczba_sekund_miedzy_datami / $ liczba_sekund_w_roku);   if ($ liczba_lat> 0)      $ string_liczba_lat = "years: $ liczba_lat";   else      $ string_liczba_lat = "";  The last4 lines are preparing the text (as the variable $ string_liczba_lat) ready to display on the screen showing the number of years remaining to the event. If the number of years is zero and will not display any text. Number of months The screen will show how many months to events after deducting the number of years between events. Therefore, we have a variable $ pozostała_liczba_sekund_miedzy_datami calculate the number of seconds between dates but after deducting the number of years (in seconds). The remaining part of the code is the same as calculating the difference years. Again, note that we assumed that the month has30 days which is a rounding. All code counting the number of months is shown below:   $ liczba_sekund_w_miesiacu =30 *24 * 60 * 60;   $ pozostała_liczba_sekund_miedzy_datami =    $ liczba_sekund_miedzy_datami - $ liczba_lat * $ liczba_sekund_w_roku;   $ liczba_miesiecy =    Floor ($ pozostała_liczba_sekund_miedzy_datami / $ liczba_sekund_w_miesiacu);   if ($ liczba_miesiecy> 0)         $ string_liczba_miesiecy = "month: $ liczba_miesiecy";   else         $ string_liczba_miesiecy = "";  Number of days reconciles, minutes Other days, hours, minutes, calculated in the same manner as the number of months: Define how many seconds in a day (or hour, minute) We are still the number of seconds remaining after taking into account the previously calculated number of years, months, ... We calculate the number of days (or hours, minutes) to the event by dividing the remaining number of seconds by the number of seconds in a day (or hour, minute) Defining text (string) specifies the remaining number of days (or hours, minutes) to the event as long as the number is greater than 0.   $ liczba_sekund_w_dniu =24 *60 * 60;   $ pozostała_liczba_sekund_miedzy_datami =    $ pozostała_liczba_sekund_miedzy_datami -    $ liczba_miesiecy * $ liczba_sekund_w_miesiacu;   $ liczba_dni =    Floor ($ pozostała_liczba_sekund_miedzy_datami / $ liczba_sekund_w_dniu);   if ($ liczba_dni> 0)         $ string_liczba_dni = "days: $ liczba_dni";   else         $ string_liczba_dni = "";    $ liczba_sekund_w_godzinie = 60 * 60;   $ pozostała_liczba_sekund_miedzy_datami =    $ pozostała_liczba_sekund_miedzy_datami -    $ liczba_dni * $ liczba_sekund_w_dniu;   $ liczba_godzin =    Floor ($ pozostała_liczba_sekund_miedzy_datami / $ liczba_sekund_w_godzinie);   if ($ liczba_godzin> 0)         $ string_liczba_godzin = "hours: $ liczba_godzin";   else         $ string_liczba_godzin = "";    $ liczba_sekund_w_minucie =60;   $ pozostała_liczba_sekund_miedzy_datami =    $ pozostała_liczba_sekund_miedzy_datami -    $ liczba_godzin * $ liczba_sekund_w_godzinie;   $ number_of_minutes =    Floor ($ pozostała_liczba_sekund_miedzy_datami / $ liczba_sekund_w_minucie);   if ($ number_of_minutes> 0)         $ string_liczba_minut = "minutes: $ number_of_minutes";   else         $ string_liczba_minut = "";  Number of seconds The number of seconds we do not have something special to calculate. It is the remaining number of seconds after calculating minutes. In addition, the number of seconds show ever. Why? Text (string): 0 seconds will not be anyone smite Prior information (eg minutes: 23) ended with a comma. Would be foolish to leave the comma as the last character. Therefore, it is better to show the seconds that do not finish any punctuation because it certainly would be the last time information to the event.   $ number_of_seconds =       $ pozostała_liczba_sekund_miedzy_datami -       $ number_of_minutes * $ liczba_sekund_w_minucie;   $ string_liczba_sekund = "seconds: $ number_of_seconds";  We pay the time to event It was time to make our PHP function returned text stating how much time is left for the event. First, all the variables that contain text (string) specifying the number of years, months, days, hours, minutes and seconds we combine in one variable $ string_czas_do_wydarzenia. In the language of PHP to connect to texts (strings) is a dot. Why combine texts in two lines? For readability of the text (useful in a text editor). Now just $ string_czas_do_wydarzenia text describing the exact amount of time to the events contained in the variable $ data_wydarzenia simply return to the parent function.   $ string_czas_do_wydarzenia = $ string_liczba_lat.         $ string_liczba_miesiecy. $ string_liczba_dni;   $ string_czas_do_wydarzenia. = $ string_liczba_godzin.         $ string_liczba_minut. $ string_liczba_sekund;    return $ string_czas_do_wydarzenia;  How to use our function? ZwrocStringOpisujacyCzasDoWydarzenia just wrote a function which returns a text (string) describing the time remaining until a specified event contained in the variable $ data_wydarzenia. How to use it? Define the date of the event First of all, we need to define the date of the event. This may be, for Example17 czerwca 2030 years 36 hours 14 minutes and29 seconds. We just have to remember to be saved date format, that is, lines, space, colons:        'Year-Month-Day Hour: Minute: Second' as follows:   $ data_wydarzenia = ' 2:36:29 p.m.';  The text describing the time to event Now we can use our ZwrocStringOpisujacyCzasDoWydarzenia function, which returns us to the text (string) describing the time to $ data_wydarzenia. We remember the text in the variable $ string_czas_do_wydarzenia. as follows:   $ string_czas_do_wydarzenia =         ZwrocStringOpisujacyCzasDoWydarzenia ($ data_wydarzenia);  What to do with text describing the time to the event? On this question we need to answer themselves. First of all we need to know what it means for us as defined above date of17 czerwca 2030 years 36 hours 14 minutes and 29 seconds stored in the variable $ data_wydarzenia. Let it be, for example, the end of the promotion. We assume that we just want to write text on the screen telling time to the end of the promotion. Then the easiest way to do this:   if ($ string_czas_do_wydarzenia == "")      echo 'promotion has already passed ... <br />';   else      echo 'the end of the promotion was left only'       . $ string_czas_do_wydarzenia. '<br />';  If the requested empty ZwrocStringOpisujacyCzasDoWydarzenia string (text), this means that our date is later than the time of promotion and promotion has ended. Print out this information using PHP echo function. Otherwise, (today's date is earlier than the end of the promotion or promotion lasts) we write text on the screen informing you of the time to the end of the promotion. Stamps & nbsp; means extra spaces that highlight our text describing in detail the amount of time until the end of the promotion ($ variable string_czas_do_wydarzenia). Does it have to be static? Our program has one property. After loading the page shown until the end of our promotion does not update. So once displayed text ?? for example:   By the end of the promotion was left only       years: 18 months: 11 days 2 hours: 6 minutes: 41 seconds: 26  will continue to display until the user refreshes the page or open it again. This can be easily remedied by typing in the page header command for the browser to refresh the page every time probably ?? For example, every5 seconds   <meta http-equiv = "Refresh" content = "5" />  Instead Fridays, we can insert any other number that defines the number of seconds the browser should reload the page. The disadvantage of this approach is that every time the entire page is loaded again. For heavy pages or a slow link may be weak. If you want to just text to the number of days to the event is refreshed to PHP or classic html is not suitable. We must then use of JavaScript. However, and JavaScript has its drawbacks. Not all users have JavaScript enabled ?? And if you want to statically? Then it is sufficient that the header of the website simply remove the line:        <meta http-equiv = "Refresh" content = "5" /> File with the program code The above-described program (code) can be downloaded here as a php file ready to be placed on a website. Below is the link to the full file containing program code that displays the time remaining until a specified date (17 June 2030 years 36 hours 14 minutes and 29 seconds) using the function ZwrocStringOpisujacyCzasDoWydarzenia. It is a web site (packed program zip) ready to be placed on a website - for example, to test, modify, etc.. The program calculates pzoostały time for a specific date code file that displays the time remaining for a specific date This simply unzip the file as a PHP file and put in the service wwww. The program will immediately display the number of hours for a specific date (17 June 2030 years 36 hours 14 minutes and29 seconds). The whole program code? Below is a listing of this program in the form of complete, sample web page that displays the exact time to the end of a promotion (17 June 2030 years 36 hours 14 minutes and29 seconds).   <! DOCTYPE HTML PUBLIC "- // // W3C DTD HTML4.0 Transitional // EN">   <html>   <head>   <title> Service ABC </ title>   <meta http-equiv = content-type content = "text / html; charset = iso-8859-2">   <meta http-equiv = "Content-Language" content = "en">   <meta http-equiv = "Refresh" content = "5" />   </ head>    <body>    <? php   $ data_wydarzenia = ' 2:36:29 p.m.';   $ string_czas_do_wydarzenia =     ZwrocStringOpisujacyCzasDoWydarzenia ($ data_wydarzenia);    if ($ string_czas_do_wydarzenia == "")      echo 'promotion has already passed ... <br />';   else      echo 'the end of the promotion was left only      &&&& '. $ string_czas_do_wydarzenia. '<br />';    ////////////////////////////////////////////////// ////////////////////   /// The ZwrocStringOpisujacyCzasDoWydarzenia ($ data_wydarzenia) ///   // Function returns a string (text) highlighted how the remaining time to a specific   // events contained in the variable $ data_wydarzenia   // If $ data_wydarzenia is earlier than the current date is fukcja   // returns an empty string or "".   // Argument $ data_wydarzenia share should be the form of:   // ?? Year-Month-Day Hour: Minute: Second ??   e.g. //   // ' 2:36:29 p.m.'   // which is   // June17,2030 roku 36 hours 14 minutes and 29 seconds   // Function will return a string describing the exact time remaining until the date of   // $ data_wydarzenia, for example:   // Years: 18 months: 11 days 2 hours: 6 minutes: 41 seconds: 26   ////////////////////////////////////////////////// ////////////////////   ZwrocStringOpisujacyCzasDoWydarzenia function ($ data_wydarzenia) {     $ data_aktualna = Date ('Y-m-d H: i: s');          $ liczba_sekund_dla_wydarzenia = strtotime ($ data_wydarzenia);      $ liczba_sekund_dla_aktualnej_daty = strtotime ($ data_aktualna);       $ liczba_sekund_miedzy_datami = $ liczba_sekund_dla_wydarzenia -        $ liczba_sekund_dla_aktualnej_daty;      if ($ liczba_sekund_miedzy_datami <= 0)         return "";       $ liczba_sekund_w_roku =365 *24 * 60 * 60;      $ liczba_lat =        Floor ($ liczba_sekund_miedzy_datami / $ liczba_sekund_w_roku);      if ($ liczba_lat> 0)         $ string_liczba_lat = "years: $ liczba_lat";      else         $ string_liczba_lat = "";       $ liczba_sekund_w_miesiacu =30 *24 * 60 * 60;      $ pozostała_liczba_sekund_miedzy_datami =        $ liczba_sekund_miedzy_datami - $ liczba_lat * $ liczba_sekund_w_roku;      $ liczba_miesiecy =   Floor ($ pozostała_liczba_sekund_miedzy_datami / $ liczba_sekund_w_miesiacu);      if ($ liczba_miesiecy> 0)         $ string_liczba_miesiecy = "month: $ liczba_miesiecy";      else         $ string_liczba_miesiecy = "";       $ liczba_sekund_w_dniu =24 *60 * 60;      $ pozostała_liczba_sekund_miedzy_datami =        $ pozostała_liczba_sekund_miedzy_datami -        $ liczba_miesiecy * $ liczba_sekund_w_miesiacu;      $ liczba_dni =        Floor ($ pozostała_liczba_sekund_miedzy_datami / $ liczba_sekund_w_dniu);      if ($ liczba_dni> 0)         $ string_liczba_dni = "days: $ liczba_dni";      else         $ string_liczba_dni = "";       $ liczba_sekund_w_godzinie = 60 * 60;      $ pozostała_liczba_sekund_miedzy_datami =        $ pozostała_liczba_sekund_miedzy_datami        - $ Liczba_dni * $ liczba_sekund_w_dniu;      $ liczba_godzin =   Floor ($ pozostała_liczba_sekund_miedzy_datami / $ liczba_sekund_w_godzinie);      if ($ liczba_godzin> 0)         $ string_liczba_godzin = "hours: $ liczba_godzin";      else         $ string_liczba_godzin = "";       $ liczba_sekund_w_minucie =60;      $ pozostała_liczba_sekund_miedzy_datami =        $ pozostała_liczba_sekund_miedzy_datami -        $ liczba_godzin * $ liczba_sekund_w_godzinie;      $ number_of_minutes =   Floor ($ pozostała_liczba_sekund_miedzy_datami / $ liczba_sekund_w_minucie);      if ($ number_of_minutes> 0)         $ string_liczba_minut = "minutes: $ number_of_minutes";      else         $ string_liczba_minut = "";       $ number_of_seconds = $ pozostała_liczba_sekund_miedzy_datami -        $ number_of_minutes * $ liczba_sekund_w_minucie;      $ string_liczba_sekund = "seconds: $ number_of_seconds";       $ string_czas_do_wydarzenia = $ string_liczba_lat.        $ string_liczba_miesiecy. $ string_liczba_dni;      $ string_czas_do_wydarzenia. = $ string_liczba_godzin.        $ string_liczba_minut. $ string_liczba_sekund;       return $ string_czas_do_wydarzenia;   }   ?>    </ body>   </ html>

Tomasz Modrzejewski
by Tomasz Modrzejewski , Programmer , Company Skraw-Mech

Timing amount of time to a specific date Scripts PHP, mySQL The exact time to a specific date Often we want to make our page showed in great detail the time to a specific date - for example: end of the promotion date of birth solar eclipse ... Thanks to this article you will be able to see your own text with the exact time remaining for you to important events. The on-screen text will be included number years months days hours minutes seconds the rest of the event. How to use this article? Article: At the beginning describes a function in PHP that returns a text (string) describing the time remaining until a certain date. This feature can copy and paste into your own program and use freely. Shows how to use the function described. At the end of this document for a complete, sample web page with PHP code metering the exact time to the end of a fictitious promotion. This website uses previously written function. You can paste this page into your site, test, modify, adapt to their needs. Description of functions ZwrocStringOpisujacyCzasDoWydarzenia What does the ZwrocStringOpisujacyCzasDoWydarzenia The key feature of our program is PHP ZwrocStringOpisujacyCzasDoWydarzenia declared as follows:   ZwrocStringOpisujacyCzasDoWydarzenia function ($ data_wydarzenia) {  }  Its argument is a string (text) contains the date of the event ($ data_wydarzenia) format as follows:        'Year-Month-Day Hour: Minute: Second' For example, $ data_wydarzenia can be either:        ' 2:36:29 p.m.' which means 17 June2030 roku 36 hours 14 minutes and29 seconds. ZwrocStringOpisujacyCzasDoWydarzenia function returns a text (string) describing the time remaining until the events contained in the variable $ data_wydarzenia for example:        years: 18 months: 11 days 2 hours: 6 minutes: 41 seconds: 26 which means that the date contained in the variable $ data_wydarzenia remained 18 years,11 months, 2 days,6 hours, 41 minutes and26 seconds. Date of current To calculate the difference between the current date and the date contained in the variable $ data_wydarzenia need to get the current date in the same format as the date contained in the variable $ data_wydarzenia. PHP function date Date allows you to download in any format. That's why we call Date as follows:   $ data_aktualna = Date ('Y-m-d H: i: s');  This means that: Year, month and day are separated by dashes (-) Year will be displayed in the form of4 characters (Y) Month will be displayed in the form of two characters (m) The day will be displayed in the form of two characters (d) After a space will be displayed at the 2 characters in24 hour format (H) After the colon will show minutes as 2 characters (and) After the colon will appear second as 2 characters (s) Everything is good, but we need not two dates and the difference in hours between two dates. Number of seconds since January1,1970 PHP function strtotime calculates how many seconds have passed since January1,1970. The name of this function, you can expand on Page To Time or Replace String On Time. In this way we change the date to the number of seconds that have elapsed between the given date and January1,1970. So now we create two variables that calculate how many seconds have elapsed since January1,1970 for both our dates:   $ liczba_sekund_dla_wydarzenia = strtotime ($ data_wydarzenia);   $ liczba_sekund_dla_aktualnej_daty = strtotime ($ data_aktualna);  What if the date of the event has already passed? We can now calculate how many seconds divides the current date and event ($ liczba_sekund_miedzy_datami):   $ liczba_sekund_miedzy_datami =         $ liczba_sekund_dla_wydarzenia - $ liczba_sekund_dla_aktualnej_daty;   if ($ liczba_sekund_miedzy_datami <= 0)      return "";  If the difference in seconds between the difference is negative it means that the time has passed and events turn an empty string (empty string) as well as exit our function. The difference of years between dates We have a number of seconds between dates (variable $ liczba_sekund_miedzy_datami). However, we are interested in at the beginning of the number of years between the dates. Note that the number of seconds in a year is:     iczba_dni_w_roku * liczb_godzin_w_dniu * liczba_minut_w_godzinie * liczba_sekund_w minutes or     365 *24 * 60 * 60 This value will not count (why bother when we have computers!) Just remember in $ liczba_sekund_w_roku. We note here a weakness of our program. Does not account for leap years have 366 days in May. Now just divide $ liczba_sekund_miedzy_datami by $ liczba_sekund_w_roku to have the number of years between the dates (remember the $ liczba_lat). Get a fraction. If the events left half of the year (0.5) is obviously a 0 full years remaining to the event. Therefore, the resulting number of years we round down using PHP fukcji Floor. Full code executing these tasks are listed below:   $ liczba_sekund_w_roku =365 *24 * 60 * 60;   $ liczba_lat = Floor ($ liczba_sekund_miedzy_datami / $ liczba_sekund_w_roku);   if ($ liczba_lat> 0)      $ string_liczba_lat = "years: $ liczba_lat";   else      $ string_liczba_lat = "";  The last4 lines are preparing the text (as the variable $ string_liczba_lat) ready to display on the screen showing the number of years remaining to the event. If the number of years is zero and will not display any text. Number of months The screen will show how many months to events after deducting the number of years between events. Therefore, we have a variable $ pozostała_liczba_sekund_miedzy_datami calculate the number of seconds between dates but after deducting the number of years (in seconds). The remaining part of the code is the same as calculating the difference years. Again, note that we assumed that the month has30 days which is a rounding. All code counting the number of months is shown below:   $ liczba_sekund_w_miesiacu =30 *24 * 60 * 60;   $ pozostała_liczba_sekund_miedzy_datami =    $ liczba_sekund_miedzy_datami - $ liczba_lat * $ liczba_sekund_w_roku;   $ liczba_miesiecy =    Floor ($ pozostała_liczba_sekund_miedzy_datami / $ liczba_sekund_w_miesiacu);   if ($ liczba_miesiecy> 0)         $ string_liczba_miesiecy = "month: $ liczba_miesiecy";   else         $ string_liczba_miesiecy = "";  Number of days reconciles, minutes Other days, hours, minutes, calculated in the same manner as the number of months: Define how many seconds in a day (or hour, minute) We are still the number of seconds remaining after taking into account the previously calculated number of years, months, ... We calculate the number of days (or hours, minutes) to the event by dividing the remaining number of seconds by the number of seconds in a day (or hour, minute) Defining text (string) specifies the remaining number of days (or hours, minutes) to the event as long as the number is greater than 0.   $ liczba_sekund_w_dniu =24 *60 * 60;   $ pozostała_liczba_sekund_miedzy_datami =    $ pozostała_liczba_sekund_miedzy_datami -    $ liczba_miesiecy * $ liczba_sekund_w_miesiacu;   $ liczba_dni =    Floor ($ pozostała_liczba_sekund_miedzy_datami / $ liczba_sekund_w_dniu);   if ($ liczba_dni> 0)         $ string_liczba_dni = "days: $ liczba_dni";   else         $ string_liczba_dni = "";    $ liczba_sekund_w_godzinie = 60 * 60;   $ pozostała_liczba_sekund_miedzy_datami =    $ pozostała_liczba_sekund_miedzy_datami -    $ liczba_dni * $ liczba_sekund_w_dniu;   $ liczba_godzin =    Floor ($ pozostała_liczba_sekund_miedzy_datami / $ liczba_sekund_w_godzinie);   if ($ liczba_godzin> 0)         $ string_liczba_godzin = "hours: $ liczba_godzin";   else         $ string_liczba_godzin = "";    $ liczba_sekund_w_minucie =60;   $ pozostała_liczba_sekund_miedzy_datami =    $ pozostała_liczba_sekund_miedzy_datami -    $ liczba_godzin * $ liczba_sekund_w_godzinie;   $ number_of_minutes =    Floor ($ pozostała_liczba_sekund_miedzy_datami / $ liczba_sekund_w_minucie);   if ($ number_of_minutes> 0)         $ string_liczba_minut = "minutes: $ number_of_minutes";   else         $ string_liczba_minut = "";  Number of seconds The number of seconds we do not have something special to calculate. It is the remaining number of seconds after calculating minutes. In addition, the number of seconds show ever. Why? Text (string): 0 seconds will not be anyone smite Prior information (eg minutes: 23) ended with a comma. Would be foolish to leave the comma as the last character. Therefore, it is better to show the seconds that do not finish any punctuation because it certainly would be the last time information to the event.   $ number_of_seconds =       $ pozostała_liczba_sekund_miedzy_datami -       $ number_of_minutes * $ liczba_sekund_w_minucie;   $ string_liczba_sekund = "seconds: $ number_of_seconds";  We pay the time to event It was time to make our PHP function returned text stating how much time is left for the event. First, all the variables that contain text (string) specifying the number of years, months, days, hours, minutes and seconds we combine in one variable $ string_czas_do_wydarzenia. In the language of PHP to connect to texts (strings) is a dot. Why combine texts in two lines? For readability of the text (useful in a text editor). Now just $ string_czas_do_wydarzenia text describing the exact amount of time to the events contained in the variable $ data_wydarzenia simply return to the parent function.   $ string_czas_do_wydarzenia = $ string_liczba_lat.         $ string_liczba_miesiecy. $ string_liczba_dni;   $ string_czas_do_wydarzenia. = $ string_liczba_godzin.         $ string_liczba_minut. $ string_liczba_sekund;    return $ string_czas_do_wydarzenia;  How to use our function? ZwrocStringOpisujacyCzasDoWydarzenia just wrote a function which returns a text (string) describing the time remaining until a specified event contained in the variable $ data_wydarzenia. How to use it? Define the date of the event First of all, we need to define the date of the event. This may be, for Example17 czerwca 2030 years 36 hours 14 minutes and29 seconds. We just have to remember to be saved date format, that is, lines, space, colons:        'Year-Month-Day Hour: Minute: Second' as follows:   $ data_wydarzenia = ' 2:36:29 p.m.';  The text describing the time to event Now we can use our ZwrocStringOpisujacyCzasDoWydarzenia function, which returns us to the text (string) describing the time to $ data_wydarzenia. We remember the text in the variable $ string_czas_do_wydarzenia. as follows:   $ string_czas_do_wydarzenia =         ZwrocStringOpisujacyCzasDoWydarzenia ($ data_wydarzenia);  What to do with text describing the time to the event? On this question we need to answer themselves. First of all we need to know what it means for us as defined above date of17 czerwca 2030 years 36 hours 14 minutes and 29 seconds stored in the variable $ data_wydarzenia. Let it be, for example, the end of the promotion. We assume that we just want to write text on the screen telling time to the end of the promotion. Then the easiest way to do this:   if ($ string_czas_do_wydarzenia == "")      echo 'promotion has already passed ... <br />';   else      echo 'the end of the promotion was left only'       . $ string_czas_do_wydarzenia. '<br />';  If the requested empty ZwrocStringOpisujacyCzasDoWydarzenia string (text), this means that our date is later than the time of promotion and promotion has ended. Print out this information using PHP echo function. Otherwise, (today's date is earlier than the end of the promotion or promotion lasts) we write text on the screen informing you of the time to the end of the promotion. Stamps & nbsp; means extra spaces that highlight our text describing in detail the amount of time until the end of the promotion ($ variable string_czas_do_wydarzenia). Does it have to be static? Our program has one property. After loading the page shown until the end of our promotion does not update. So once displayed text ?? for example:   By the end of the promotion was left only       years: 18 months: 11 days 2 hours: 6 minutes: 41 seconds: 26  will continue to display until the user refreshes the page or open it again. This can be easily remedied by typing in the page header command for the browser to refresh the page every time probably ?? For example, every5 seconds   <meta http-equiv = "Refresh" content = "5" />  Instead Fridays, we can insert any other number that defines the number of seconds the browser should reload the page. The disadvantage of this approach is that every time the entire page is loaded again. For heavy pages or a slow link may be weak. If you want to just text to the number of days to the event is refreshed to PHP or classic html is not suitable. We must then use of JavaScript. However, and JavaScript has its drawbacks. Not all users have JavaScript enabled ?? And if you want to statically? Then it is sufficient that the header of the website simply remove the line:        <meta http-equiv = "Refresh" content = "5" /> File with the program code The above-described program (code) can be downloaded here as a php file ready to be placed on a website. Below is the link to the full file containing program code that displays the time remaining until a specified date (17 June 2030 years 36 hours 14 minutes and 29 seconds) using the function ZwrocStringOpisujacyCzasDoWydarzenia. It is a web site (packed program zip) ready to be placed on a website - for example, to test, modify, etc.. The program calculates pzoostały time for a specific date code file that displays the time remaining for a specific date This simply unzip the file as a PHP file and put in the service wwww. The program will immediately display the number of hours for a specific date (17 June 2030 years 36 hours 14 minutes and29 seconds). The whole program code? Below is a listing of this program in the form of complete, sample web page that displays the exact time to the end of a promotion (17 June 2030 years 36 hours 14 minutes and29 seconds).   <! DOCTYPE HTML PUBLIC "- // // W3C DTD HTML4.0 Transitional // EN">   <html>   <head>   <title> Service ABC </ title>   <meta http-equiv = content-type content = "text / html; charset = iso-8859-2">   <meta http-equiv = "Content-Language" content = "en">   <meta http-equiv = "Refresh" content = "5" />   </ head>    <body>    <? php   $ data_wydarzenia = ' 2:36:29 p.m.';   $ string_czas_do_wydarzenia =     ZwrocStringOpisujacyCzasDoWydarzenia ($ data_wydarzenia);    if ($ string_czas_do_wydarzenia == "")      echo 'promotion has already passed ... <br />';   else      echo 'the end of the promotion was left only      &&&& '. $ string_czas_do_wydarzenia. '<br />';    ////////////////////////////////////////////////// ////////////////////   /// The ZwrocStringOpisujacyCzasDoWydarzenia ($ data_wydarzenia) ///   // Function returns a string (text) highlighted how the remaining time to a specific   // events contained in the variable $ data_wydarzenia   // If $ data_wydarzenia is earlier than the current date is fukcja   // returns an empty string or "".   // Argument $ data_wydarzenia share should be the form of:   // ?? Year-Month-Day Hour: Minute: Second ??   e.g. //   // ' 2:36:29 p.m.'   // which is   // June17,2030 roku 36 hours 14 minutes and 29 seconds   // Function will return a string describing the exact time remaining until the date of   // $ data_wydarzenia, for example:   // Years: 18 months: 11 days 2 hours: 6 minutes: 41 seconds: 26   ////////////////////////////////////////////////// ////////////////////   ZwrocStringOpisujacyCzasDoWydarzenia function ($ data_wydarzenia) {     $ data_aktualna = Date ('Y-m-d H: i: s');          $ liczba_sekund_dla_wydarzenia = strtotime ($ data_wydarzenia);      $ liczba_sekund_dla_aktualnej_daty = strtotime ($ data_aktualna);       $ liczba_sekund_miedzy_datami = $ liczba_sekund_dla_wydarzenia -        $ liczba_sekund_dla_aktualnej_daty;      if ($ liczba_sekund_miedzy_datami <= 0)         return "";       $ liczba_sekund_w_roku =365 *24 * 60 * 60;      $ liczba_lat =        Floor ($ liczba_sekund_miedzy_datami / $ liczba_sekund_w_roku);      if ($ liczba_lat> 0)         $ string_liczba_lat = "years: $ liczba_lat";      else         $ string_liczba_lat = "";       $ liczba_sekund_w_miesiacu =30 *24 * 60 * 60;      $ pozostała_liczba_sekund_miedzy_datami =        $ liczba_sekund_miedzy_datami - $ liczba_lat * $ liczba_sekund_w_roku;      $ liczba_miesiecy =   Floor ($ pozostała_liczba_sekund_miedzy_datami / $ liczba_sekund_w_miesiacu);      if ($ liczba_miesiecy> 0)         $ string_liczba_miesiecy = "month: $ liczba_miesiecy";      else         $ string_liczba_miesiecy = "";       $ liczba_sekund_w_dniu =24 *60 * 60;      $ pozostała_liczba_sekund_miedzy_datami =        $ pozostała_liczba_sekund_miedzy_datami -        $ liczba_miesiecy * $ liczba_sekund_w_miesiacu;      $ liczba_dni =        Floor ($ pozostała_liczba_sekund_miedzy_datami / $ liczba_sekund_w_dniu);      if ($ liczba_dni> 0)         $ string_liczba_dni = "days: $ liczba_dni";      else         $ string_liczba_dni = "";       $ liczba_sekund_w_godzinie = 60 * 60;      $ pozostała_liczba_sekund_miedzy_datami =        $ pozostała_liczba_sekund_miedzy_datami        - $ Liczba_dni * $ liczba_sekund_w_dniu;      $ liczba_godzin =   Floor ($ pozostała_liczba_sekund_miedzy_datami / $ liczba_sekund_w_godzinie);      if ($ liczba_godzin> 0)         $ string_liczba_godzin = "hours: $ liczba_godzin";      else         $ string_liczba_godzin = "";       $ liczba_sekund_w_minucie =60;      $ pozostała_liczba_sekund_miedzy_datami =        $ pozostała_liczba_sekund_miedzy_datami -        $ liczba_godzin * $ liczba_sekund_w_godzinie;      $ number_of_minutes =   Floor ($ pozostała_liczba_sekund_miedzy_datami / $ liczba_sekund_w_minucie);      if ($ number_of_minutes> 0)         $ string_liczba_minut = "minutes: $ number_of_minutes";      else         $ string_liczba_minut = "";       $ number_of_seconds = $ pozostała_liczba_sekund_miedzy_datami -        $ number_of_minutes * $ liczba_sekund_w_minucie;      $ string_liczba_sekund = "seconds: $ number_of_seconds";       $ string_czas_do_wydarzenia = $ string_liczba_lat.        $ string_liczba_miesiecy. $ string_liczba_dni;      $ string_czas_do_wydarzenia. = $ string_liczba_godzin.        $ string_liczba_minut. $ string_liczba_sekund;       return $ string_czas_do_wydarzenia;   }   ?>    </ body>   </ html>

Abdul Khader Shaik
by Abdul Khader Shaik , Cyber Crime Lawyer , Grofers

There are many ways to calculate.,

BEST SIMPLEST WAY IS BY MICROSOFT EXCEL

 

if you still need a program here C-Program to calculate

 

#include <stdio.h>

#include <stdlib.h>

 

void leap(int year1, int year2, int *leap1, int *leap2);

void date(int *month1, int *day1, int *year1, int *month2, int *day2, int *year2, int *leap1, int *leap2);

 

int main(void)

{

        int month1, day1, year1, month2, day2, year2, leap1, leap2;

        int daysPerMonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};

        int daysPerMonthLeap[] = {31,29,31,30,31,30,31,31,30,31,30,31};

 

        leap(year1, year2, &leap1, &leap2);

        date(&month1, &day1, &year1, &month2, &day2, &year2, &leap1, &leap2);

 

        if(year1 == year2)

        {

                int i, total;

 

                if(month1 == month2)                            // Total days if month1 == month2

                {

                        total = day2 - day1;

                        printf("There are %d days between the two dates.", total);

                }

                else

                {

                    if(leap1 ==1)

                        total = daysPerMonthLeap[month1] - day1;

                    else

                        total = daysPerMonth[month1] - day1;

 

                    for(i = month1 +1; i < month2; i++)        // Days remaining between dates (excluding last month)

                    {

                        if(leap1 ==1)

                            total += daysPerMonthLeap[i];

                        else

                            total += daysPerMonth[i];

                    }

 

                    total += day2;                              // Final sum of days between dates (including last month)

 

                    printf("There are %d days between the two dates.", total);

                }

        }

        else                                                    // If year1 != year2 ...

        {

                int i, total, century1 = ((year1 /100) +1) *100, falseleap =0;

 

                if(leap1 ==1)

                    total = daysPerMonthLeap[month1] - day1;

                else

                    total = daysPerMonth[month1] - day1;

 

                for(i = month1 +1; i <=12; i++)               // Day remaining in first year

                {

                    if(leap1 ==1)

                        total += daysPerMonthLeap[i];

                    else

                        total += daysPerMonth[i];

                }

 

                for(i =1; i < month2; i++)                     // Days remaining in final year (excluding last month)

                {

                    if(leap2 ==1)

                        total += daysPerMonthLeap[i];

                    else

                        total += daysPerMonth[i];

                }

 

                int leapcount1 = year1 /4;                     // Leap years prior to and including first year

                int leapcount2 = year2 /4;                     // Leap years prior to and NOT including final year

                if(year2 %4 ==0)

                        leapcount2 -=1;

 

                int leaptotal = leapcount2 - leapcount1;        // Leap years between dates

 

                for(i = century1; i < year2; i +=100)          // "False" leap years (divisible by100 but not400)

                {

                        if((i %400) !=0)

                                falseleap +=1;

                }

 

                total +=365 * (year2 - year1 -1) + day2 + leaptotal - falseleap;      // Final calculation

                printf("There are %d days between the two dates.", total);

        }

        return0;

}

 

void leap(int year1, int year2, int *leap1, int *leap2)             // Determines if first and final years are leap years

{

        if(year1 %4 ==0)

        {

                if(year1 %100 ==0)

                {

                        if(year1 %400 ==0)

                                *leap1 =1;

                        else

                                *leap1 =0;

                }

                else

                        *leap1 =1;

        }

        else

                *leap1 =0;

 

        if(year2 %4 ==0)

        {

                if(year2 %100 ==0)

                {

                        if(year2 %400 ==0)

                                *leap2 =1;

                        else

                                *leap2 =0;

                                }

                else

                        *leap2 =1;

        }

        else

                *leap2 =0;

}

 

void date(int *month1, int *day1, int *year1, int *month2, int *day2, int *year2, int *leap1, int *leap2)

{

        for(;;)                     // Infinite loop (exited upon valid input)

        {

                int fail =0;

                printf("\\nEnter first date: ");

                scanf("%d/%d/%d", month1, day1, year1);

                if(*month1 <1 || *month1 >12)

                {

                        printf("Invalid entry for month.\\n");

                        fail +=1;

                }

                if(*day1 <1 || *day1 >31)

                {

                        printf("Invalid entry for day.\\n");

                        fail +=1;

                }

                if(*year1 <1)

                {

                        printf("Invalid entry for year.\\n");

                        fail +=1;

                }

                if(daysPerMonth[month1] ==30 && *day1 >30)

                {

                        printf("Invalid month and day combination.\\n");

                        fail +=1;

                }

                if(*month1 ==2)

                {

                        if(*leap1 ==1 && *day1 >29)

                        {

                            printf("Invalid month and day combination.\\n");

                            fail +=1;

                        }

                        else if(*day1 >28)

                        {

                            printf("Invalid month and day combination.\\n");

                            fail +=1;

                        }

                }

                if(fail >0)

                        continue;

                else

                        break;

        }

 

        for(;;)

        {

                int fail =0;

                printf("\\nEnter second date: ");

                scanf("%d/%d/%d", month2, day2, year2);

                if(*year1 == *year2)

                {

                        if(*month1 > *month2)

                        {

                                printf("Invalid entry.\\n");

                                fail +=1;

                        }

                        if(*month1 == *month2 && *day1 > *day2)

                        {

                                printf("Invalid entry.\\n");

                                fail +=1;

                        }

                }

                if(*month2 <1 || *month2 >12)

                {

                        printf("Invalid entry for month.\\n");

                        fail +=1;

                }

                if(*day2 <1 || *day2 >31)

                {

                        printf("Invalid entry for day.\\n");

                        fail +=1;

                }

                if(*year2 <1)

                {

                        printf("Invalid entry for year.\\n");

                        fail +=1;

                }

                if(daysPerMonth[month2] ==30 && *day2 >30)

                {

                        printf("Invalid month and day combination.\\n");

                        fail +=1;

                }

                if(*month2 ==2)

                {

                        if(*leap2 ==1 && *day2 >29)

                        {

                            printf("Invalid month and day combination.\\n");

                            fail +=1;

                        }

                        else if(*day2 >28)

                        {

                            printf("Invalid month and day combination.\\n");

                            fail +=1;

                        }

                }

                if(fail >0)

                        continue;

                else

                        break;

        }

}

Daanish Rumani
by Daanish Rumani , Product Manager , Publicis Sapient

In C# var date1 = new DateTime(2000,1,1); var date2 = new DateTime(2014,8,10); var difference = date2 - date1; // difference is a TimeSpan object In Java Date date1 = new GregorianCalendar(2000,1,1,0,0,0).getTime(); Date date2 = new GregorianCalendar(2014,8,10,0,0,0).getTime(); long diffInMillis = today.getTime() - d1.getTime(); // diffInMillis has the difference in milliseconds

George Dimitrov
by George Dimitrov , Unix System Administrator , ADVANCED.IO

Lets do it in a simple javascript with the timeDiff() function Example1:

 

var date1 = new Date('01/01/2000');

var date2 = new Date('10/08/2014');

var timeDiff = Math.abs(date2.getTime() - date1.getTime());

var diffDays = Math.ceil(timeDiff / (1000 *3600 *24)); 

 

alert(diffDays + ' day\\\\'s');

 

Answer:  5394 day's

Working example: http://jsfiddle.net/garicool/qnfsydmp/

 

And a little more complex solution since I did not fit the question requirments Example2:

var DateDiff = {

 

    inDays: function(d1, d2) {

        var t2 = d2.getTime();

        var t1 = d1.getTime();

 

        return parseInt((t2-t1)/(24*3600*1000));

    },

 

    inWeeks: function(d1, d2) {

        var t2 = d2.getTime();

        var t1 = d1.getTime();

 

        return parseInt((t2-t1)/(24*3600*1000*7));

    },

 

    inMonths: function(d1, d2) {

        var d1Y = d1.getFullYear();

        var d2Y = d2.getFullYear();

        var d1M = d1.getMonth();

        var d2M = d2.getMonth();

 

        return (d2M+12*d2Y)-(d1M+12*d1Y);

    },

 

    inYears: function(d1, d2) {

        return d2.getFullYear()-d1.getFullYear();

    }

}

 

var dString1 = "01/01/2000";

var dString2 = "10/08/2014";

 

var d1 = new Date(dString1);

var d2 = new Date(dString2);

 

document.write("<br />Number of <b>days</b> since "+dString1+": "+DateDiff.inDays(d1, d2));

document.write("<br />Number of <b>weeks</b> since "+dString1+": "+DateDiff.inWeeks(d1, d2));

document.write("<br />Number of <b>months</b> since "+dString1+": "+DateDiff.inMonths(d1, d2));

document.write("<br />Number of <b>years</b> since "+dString1+": "+DateDiff.inYears(d1, d2));

 

 

Working example: http://jsfiddle.net/garicool/rh2thnru/

Muhammad Majid Saleem
by Muhammad Majid Saleem , Senior PHP Developer / Project Manager , SwaamTech

You didn't mention that in which language you want to calculate differences between two dates.

 

PHP Date Difference Calculation:

http://php.net/manual/en/datetime.diff.php

 

MySQL Date Difference Calculation:

http://www.w3schools.com/sql/func_datediff_mysql.asp

You can convert time into Years, Months and Days from difference.

Muktar SayedSaleh
by Muktar SayedSaleh , Software Engineering Manager , AIRASIA

 

 $date1 = "";$date2 = "";$diff = abs(strtotime($date2) - strtotime($date1));$years = floor($diff / (365*60*60*24));$months = floor(($diff - $years *365*60*60*24) / (30*60*60*24));$days = floor(($diff - $years *365*60*60*24 - $months*30*60*60*24)/ (60*60*24));printf("%d years, %d months, %d days\\n", $years, $months, $days);/* good luck :) */

/// in delphi

Procedure Calcul (FromDate, ToDate: TDateTime;  var Years, Months, Days: Integer);

var  FromY, FromM, FromD,    // from date 

        ToY, ToM, ToD: Word;    // to date 

        TmpDate: TDateTime;

         PreviousMonth: Byte; 

         DaysInMonth: Byte;

begin 

DecodeDate(ToDate, ToY, ToM, ToD);

DecodeDate(FromDate, FromY, FromM, FromD); 

Years := ToY - FromY; 

Months := ToM - FromM; 

Days := ToD - FromD; 

        if Days <0 then 

              begin

              Dec(Months);   

              PreviousMonth := ToM + (Byte(ToM =1) *12) -1;

             case PreviousMonth of     

            1,3,5,7,8,10,12: DaysInMonth :=31;     

            4,6,9,11       : DaysInMonth :=30;     

             else

            DaysInMonth :=28 + Byte(IsLeapYear(ToY));   

            end;   

Days := DaysInMonth - Abs(Days); 

end; 

if Months <0 then 

begin   

Dec(Years);

Months :=12 - Abs(Months); 

end;

end;

Muhammad Qasim
by Muhammad Qasim , Construction Manager , H.A. J Contracting Company

Very Simple and the shortcut method just follow the following steps:

1- Open empty Excel sheet.

2- Write in first cell the present date ( or any date you want ).

3- Write in the second cell the previous date ( or any date which is in past ).

4- Now below that cell do this procedure    =(click on First cell )-(click on second cell)  and click enter. You will see a number.

5- Now select that cell and click on press right side of mouse. A new pop up window will open select”Format Cells " then click enter on that.

6- You will see a new window under the category heading check the list for  "Custom" click on that.

7- On the same window more options will be displayed at right side go down and select " dd-mm-yy" click on ok .

8- Now look at the cell of Excel sheet. You will find that the previous answer of digits converts to the format of days, months and years.

>>> This is the solution you can see how many days, months and years passed during to different dates.

 

Thanks for reading.

Mohamed Azmy
by Mohamed Azmy , Web Designer / Developer , N++ Studios

convert both to timestamps and simply subtract...

You can try this ... This is Javascript Age caluclator ....

 

function getAge() {

            var dob = document.getElementById("txtDateofBirth").value;//get date of birth ebtered in textbox ID txtDOB

            var curdate = new Date();                                      //get Current date

            dob = new Date(Date.parse(dob));                        //convert dob to javascript date formate

            day = curdate.getDate() - dob.getDate();

            //month = curdate.getMonth() - dob.getMonth();

            year = curdate.getFullYear() - dob.getFullYear();

 

            if (day <0) {

                day = curdate.getDate() +3 - dob.getDate();

                month = curdate.getMonth() -1  - dob.getMonth();

            }

            if (month <0) {

                month = curdate.getMonth() +11 - dob.getMonth();

                year = curdate.getFullYear() -1 - dob.getFullYear();

            }

            //  alert("AGE:" + year + " Years," + month + " Months, " + day + " Days.");       //Show age in alert

 

 

            document.getElementById("lblDateCount").innerHTML = year + " Years," + month + " Months, " + day + " Days.";//set it to label

        }

 

***** All the Best *********

Thanks With regards 

Prasad Anumolu

 

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.