Jump to content

Change date format in script


wagga2650

Recommended Posts

I have a script that shows how many days between given dates but you have to enter the date in mm/dd/yyy format. I would like to change it so I can enter it in dd/mm/yyy format.

 

Here is the script below. Any help would be greatly appreciated, thanks

 

Head code

<title>Datediff</title>

<script type='text/javascript'>
  var msPerSec  = 1000                           // # milliseconds / Second
  var secPerMin = 60                             // # Seconds / Minute
  var secPerHr  = 60     * secPerMin             // # Seconds / Hour
  var secPerDay = 24     * secPerHr              // # Seconds / Day
  var secPerYr  = 365.25 * secPerDay             // # Seconds / Year

  function field( id ) {
    var ele = document.getElementById( id )
    if ( !ele ) {
      alert( 'Element not found.  id="' + id + '"' )
    }
    return ele
  }

  function setVal( id, val ) {
    var ele = field( id )
    if ( ele ) {
      ele.innerHTML = val
    }
  }

  function getVal( id ) {
    var ele = field( id )
    var result = null
    if ( ele ) {
      result = ele.value
    }
    return result
  }

  function CalculateDiff( d1, d2 ) {
    var date1  = new Date( getVal( d1 ) )
    var date2  = new Date( getVal( d2 ) )
    var diff   = Math.floor( Math.abs( date2 - date1 ) / msPerSec )

    var years  = Math.floor( diff / secPerYr )

    var rest   = diff - years * secPerYr
    var days   = Math.floor( rest / secPerDay )
    setVal( 'days' , days  )
        rest   = rest - days * secPerDay
    var hours  = Math.floor( rest / secPerHr )
        rest   = rest - hours * secPerHr
    var mins   = Math.floor( rest / secPerMin )
        rest   = rest - mins * secPerMin



  }
</script>

 

Body COde

 

<form name='' action=''>
  <br>Date 1 <input type='text' value='11/01/2006' id='date1'/>
  <br>Date 2 <input type='text' value='12/29/2007' id='date2'/>
<br>
  <input type='button' value='Calculate difference' onclick='CalculateDiff("date1","date2");'>
<br> Calculated Difference
  <table border='1'>

    <tr>
      <th>Days </th><td><textarea name='days' rows='1' cols='8' id='days'>   </textarea></td>
    </tr>
  
  </table>
</form>

Link to comment
https://forums.phpfreaks.com/topic/215533-change-date-format-in-script/
Share on other sites

Well, the code you have is flawed to begin with. For example:

 

var years  = Math.floor( diff / secPerYr )

 

 

That assumes that there are the same number of seconds per year. But, that is not the case with leap years and you would get inaccurate results.

 

Here is a rewrite of what you had plus some code of mine modified for a date in the format you specified. I did some testing but not comprehensive

 

<html><head><title>Datediff</title><script type='text/javascript'>//****************************************************************//// FUNCTION: isDate (dateStr)                                     ////                                                                //// This function takes a string variable and verifies if it is a  //// valid date or not. Dates must be in the format of dd-mm-yyyy   //// or dd/mm/yyyy. It checks to make sure the month has the proper //// number of days, based on the month. The function returns true  //// if a valid date, false if not.                                 ////                                                                //// Day/Month must be 1 or 2 digits, Year must be 2 or 4 digits.   ////****************************************************************//function isDate(dateStr){  var datePattern = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/  var matchArray = dateStr.match(datePattern);  //Check valid format  if (matchArray == null) { return false; }  day   = matchArray[1];  month = matchArray[3];  year  = matchArray[5];  // check month range  if (month < 1 || month > 12) { return false; }  //Check day range  if (day < 1 || day > 31) { return false; }  //Check months with 30 days  if ((month==4 || month==6 || month==9 || month==11) && day>30) { return false; }  //Check Feb days  if (month == 2)  {    var leapYr = (year%4 == 0 && (year%100 != 0 || year%400 == 0));    if (day > 29 || (day==29 && !leapYr)) { return false; }  }  return true;}function getDateObj(dateStr){  var datePattern = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/  var matchArray = dateStr.match(datePattern);  var dateObj = new Date(matchArray[4], matchArray[3]-1, matchArray[1], 12, 0, 0);  return dateObj;}//***************************************************************//// FUNCTION: dateDiff(Date1Obj, Date2Obj, [units], [precision])  ////                                                               //// Returns the difference between two date objects in the units  //// specified (optional, default is days). The optional precision //// parameter determines the number of decimal places the result  //// will be rounded to. Note: When the 'days' units is used and   //// precision is 0, then output will be in calendar days.         ////                                                               //// The units parameter includes the following: d=days (default), ////      h = hours, m = minutes, s = seconds, ms = milliseconds   ////***************************************************************//function dateDiff(date1Obj, date2Obj, units, precision){  //set the default untis  var units = (units)?units:'d';  var calcPrecision = (precision)?Math.pow(10, precision) : 1;  //Calculate the units divisor  switch (units)  {    case 'ms': //Milliseconds      var units = 1;      break;    case 's': //Seconds      var units = 1000;      break;    case 'm': //Minutes      var units = 1000 * 60;      break;    case 'h': //hours      var units = 1000 * 60 * 60;      break;    case 'd': //Calendar Days    default:      var units = 1000 * 60 * 60 * 24;      //Normalize time to 12:00am to count calendar days if precision = 0      if (precision==0)      {        date1Obj.setHours(0);        date2Obj.setHours(0);      }      break;  }  //Convert dates to milliseconds  var date1ms = date1Obj.getTime();  var date2ms = date2Obj.getTime();  //Calculate the difference in selected units  var difference = (date2ms - date1ms) / units;  //Convert to precision parameter  difference = (Math.round(difference*calcPrecision))/calcPrecision;  return difference;}function CalculateDiff(date1ID, date2ID){  var date1Val = getVal(date1ID);  var date2Val = getVal(date2ID);    if(!isDate(date1Val) || !isDate(date2Val))  {    return false;  }  setVal('days', dateDiff(getDateObj(date1Val), getDateObj(date2Val)));  return;}function field(id){  var ele = document.getElementById( id );  if ( !ele )  {    alert( 'Element not found.  id="' + id + '"' );  }  return ele;}function setVal(id, val){  var ele = field(id);  if (ele)  {    ele.innerHTML = val;  }}function getVal(id){  var ele = field(id);  var result = null  if (ele)  {    result = ele.value;  }  return result;}</script></head><body><form name='' action=''>  <br>Date 1 <input type='text' value='11/01/2006' id='date1'/>  <br>Date 2 <input type='text' value='12/29/2007' id='date2'/><br>  <input type='button' value='Calculate difference' onclick='CalculateDiff("date1","date2");'><br> Calculated Difference  <table border='1'>    <tr>      <th>Days </th><td><textarea name='days' rows='1' cols='8' id='days'>   </textarea></td>    </tr>    </table></form></body></html>

 

 

 

Seriously? I just rewrote that code (which originally worked for mm-dd-yyy) to work for dd-mm-yyyy as you asked.

 

I don't have the time to review and update the code again, but I think all you need to do is change

  day   = matchArray[1];
  month = matchArray[3];
  year  = matchArray[5];

To

  month   = matchArray[1];
  day = matchArray[3];
  year  = matchArray[5];

 

And

var dateObj = new Date(matchArray[4], matchArray[3]-1, matchArray[1], 12, 0, 0);

 

To

var dateObj = new Date(matchArray[4], matchArray[1]-1, matchArray[3], 12, 0, 0);

OK, maybe I am not understanding you then. I made the changes I specified above and the page then works for dates in the format mm-dd-yyyy.

 

Are you wanting users to enter dates in BOTH formats? If so, what logic do you use to determine which value is the day and which is the month? For a date where the day is >12 it can be done easliy enough, but what if the date is entered as: 2-8-2010? Is that February 8th or August 2nd?

 

I also have code that allows the user to use about any character as a delimiter (i.e. 2-15-2010 or 2.15.2010 or 2/15/2020). But, if you are going to have a problem with the user entering the month and day in different orders then I would suggest you find a javascript popup calendar to incorporate.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.