Results 1 to 7 of 7

Thread: how to change date format in script

  1. #1
    Join Date
    Aug 2010
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default how to change date format in script

    I have a script that returns the amount of days between 2 dates and I am trying to figure out how to change the date input format to dd/mm/yyy format instead of mm/dd/yyyy

    here is the script

    Head Code
    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

    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'>&nbsp;&nbsp;&nbsp;</textarea></td>
        </tr>
      
      </table>
    </form>
    any help would be greatly appreciated. Thanks in advance.

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    29,072
    Thanks
    44
    Thanked 3,216 Times in 3,178 Posts
    Blog Entries
    12

    Default

    I think you mean to dd/mm/yyyy, not dd/mm/yyy as you have in your post:

    change the date input format to dd/mm/yyy format
    If you did that 2010 would be the same as 3010 and/or be meaningless as to the year. Maybe that's what you want. But I'm going to assume you mean dd/mm/yyyy.

    Anyways, in terms of logical systems, as far as I know numbers are the only universal language. But even the symbols used to represent them vary. In this case you aren't dealing with numbers per se, rather a string which contains number characters. So, we cannot assume anything. Generally the javascript Date() object expects a string or a number of milliseconds. If it's a string, various formats are acceptable. Conceivably even this could vary on different computers, though I'm not aware of that happening. Your code uses a string. With the nn/nn/nnnn format you are limited to mm/dd/yyyy, unless something is done to change that.

    We can accept dd/mm/yyyy and rearrange it to the expected mm/dd/yyyy here by changing:

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

    Code:
      function getVal( id ) {
        var ele = field( id )
        var result = null
        if ( ele && ele.value && /^\d{2}\/\d{2}\/\d{4}$/.test(ele.value) ) {
          result = ele.value.split('/');
          result = [result[1], result[0], result[2]].join('/');
        }
        return result
      }
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Aug 2010
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Hi John,

    yes I did mean yyyy and thnaks very much for your quick and precise response it works well.

    thankyou very very much I appreciate the fact you have fixed it for me.

  4. #4
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    29,072
    Thanks
    44
    Thanked 3,216 Times in 3,178 Posts
    Blog Entries
    12

    Default

    You're welcome. I just realized though that, since months in javascript are calculated using 0 for January, not 1 as is assumed by the code, we need to make that adjustment:

    Code:
      function getVal( id ) {
        var ele = field( id )
        var result = null
        if ( ele && ele.value && /^\d{2}\/\d{2}\/\d{4}$/.test(ele.value) ) {
          result = ele.value.split('/');
          result = [result[1] - 1, result[0], result[2]].join('/');
        }
        return result
      }
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  5. #5
    Join Date
    Aug 2010
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Hi Jonh

    I have realised the code I originally posted doesnt cater for leap years and I have this code that is already in ddmmyyyy format, do you know how I would change it so I could have the option of mmddyyyy format as well as my ddmmyyyy format

    Code:
    <html>
    <head>
    
    <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='12/10/2010' id='date1'/>
      <br>Date 2 <input type='text' value='14/10/2010' 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'>&nbsp;&nbsp;&nbsp;</textarea></td>
        </tr>
     
      </table>
    </form>
    
    </body>
    </html>

  6. #6
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    29,072
    Thanks
    44
    Thanked 3,216 Times in 3,178 Posts
    Blog Entries
    12

    Default

    Code:
    <html>
    <head>
    
    <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, method)
    {
      var datePattern = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/
      var matchArray = dateStr.match(datePattern), m = method === 'mm'? 1 : 3, d = m === 1? 3 : 1;
    
      //Check valid format
      if (matchArray == null) { return false; }
    
      day   = matchArray[d];
      month = matchArray[m];
      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, method)
    {
      var matchArray = dateStr.split('/'), m = method === 'mm'? 0 : 1, d = !m? 1 : 0;
      --matchArray[m];
      var dateObj = new Date(matchArray[2], matchArray[m], matchArray[d], 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);
      var method = document.getElementById('method').checked? 'mm' : 'dd';
     
      if(!isDate(date1Val, method) || !isDate(date2Val, method))
      {
        setVal('days', '');
        alert('Invalid Input Date(s) and/or Invalid Date Format');
        return false;
      }
    
      setVal('days', dateDiff(getDateObj(date1Val, method), getDateObj(date2Val, method)));
      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='12/10/2010' id='date1'/>
      <br>Date 2 <input type='text' value='14/10/2010' id='date2'/>
      <br>Toggle Date Format <input type="checkbox" id="method" value="" onclick="document.getElementById('themethod').innerHTML = this.checked? 'mm/dd/yyyy' : 'dd/mm/yyyy';"> (currently: 
      <script type="text/javascript">
    	document.write('<span id="themethod">' + (document.getElementById('method').checked? 'mm/dd/yyyy' : 'dd/mm/yyyy') + '<\/span>');
      </script>)
    <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'>&nbsp;&nbsp;&nbsp;</textarea></td>
        </tr>
     
      </table>
    </form>
    
    </body>
    </html>
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  7. #7
    Join Date
    Aug 2014
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Hello Could you help me or give me some Pointers on my website.

    http://zkillingfloor.bugs3.com/

    Please note the name of the link Doesn't match the site Im aware of that.

    Also The links have not bean changed yet As i plan on hosting On my own Web host and the site is on a temporary host to show people what ive bean up too.

    Please Note i am aware of the Website Style sheet not supporting Other browsers other than FireFox.

    I need help with my clocks

    I want to have 2 clocks on my website one for China Time and USA time as server time.
    Last edited by Beverleyh; 08-16-2014 at 09:35 PM. Reason: Formatting

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •