How do I change date format from mm/dd/yyyy to dd/mm/year

Discussion in 'JavaScript' started by TwoTimes, Nov 24, 2009.

  1. #1
    Hello,

    Does anyone know how to change the date format from mm/dd/yyyy to dd/mm/year?

    I'm using this pregnancy calculator here:

    http://javascript.internet.com/math-related/pregnancy.html

    and I need to switch the months and days around so that days are first to be input and first to be output.
     
    TwoTimes, Nov 24, 2009 IP
  2. Mike H.

    Mike H. Peon

    Messages:
    219
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #2
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>None</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript">	
    
    	function init(){
    
    		var nDate = "11/24/2009";
    
    		var nDate = nDate.replace(/(\d{2})\/(\d{2})\/(\d{4})/, "$2/$1/$3");
    
    		alert(nDate);	
    
    	}
    
    	navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);	
    
    </script>
    </head>
    	<body>
    		
                       
                  
    	</body>
    </html>
    
    Code (markup):
     
    Mike H., Nov 24, 2009 IP
  3. TwoTimes

    TwoTimes Peon

    Messages:
    5
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks for the fast response. I'm not sure how to implement the changes.

    I tried adding <script type="text/javascript">

    function init(){

    var nDate = "11/24/2009";

    var nDate = nDate.replace(/(\d{2})\/(\d{2})\/(\d{4})/, "$2/$1/$3");

    alert(nDate);

    }

    navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);

    </script>

    In between <head></head> after the other script and that did not work. I also added this part to the original script in the head.


    function init(){

    var nDate = "11/24/2009";

    var nDate = nDate.replace(/(\d{2})\/(\d{2})\/(\d{4})/, "$2/$1/$3");

    alert(nDate);

    }

    navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);

    I'm a total javascript newbie, so if you or anyone could tell me where exactly to put the code I would really appreciate it.
     
    TwoTimes, Nov 24, 2009 IP
  4. gandalf117

    gandalf117 Active Member

    Messages:
    111
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #4
    Mike has given you a very neat solution. From all of his code all you need to implement is this one line:

    nDate = nDate.replace(/(\d{2})\/(\d{2})\/(\d{4})/, "$2/$1/$3");

    where nDate is the date that the user inputs in the input field or the date you want to change.

    All this does is that it matches the first two digit integers (expressed with d{2}) that are separated only by a forward slash /, and switches them. While it is a neat solution it has some limitations, because it will work only with forward slash as separator and with two digits for month and day. If your date is in the format 11-24-2009 or 11/1/2009 it will not work.

    You have plenty of choices. You can use Mike's way but you have to adhere to dd/mm/yyyy format or you can think of something more flexible. For example:

    function convertDate(nDate)
    {
    //this is the symbol that separates months, days and years and you can set it to anything, just pick your separator
    var separator = "/";

    //puts mm, dd and yyyy into an array
    var nDateArr = nDate.split(separator);

    //saves each argument of the array into a string starting with the day
    nDate = nDateArr[1] + separator + nDateArr[0] + separator + nDateArr[2];

    return nDate;
    }

    now all you need to do is call this function to convert the date you want to change:
    yourDate = convertDate(yourDate);

    it's not as short and neat as Mike's but is more flexible
     
    Last edited: Nov 25, 2009
    gandalf117, Nov 25, 2009 IP
  5. TwoTimes

    TwoTimes Peon

    Messages:
    5
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thanks for the help, but where exactly do I put that line? I copied and tried pasting it a lot of different places but it didn't work :(
     
    TwoTimes, Nov 26, 2009 IP
  6. gandalf117

    gandalf117 Active Member

    Messages:
    111
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #6
    Hmmm, in your case you will need to place this statement not one time but four times in order to change the input date and then the way the dates are displayed.

    1st time it changes the user input date from dd/mm/yyyy back to mm/dd/yyyy format because you have validation that requires this format in order to be accurate. I assume the user will input the date in the format you want dd/mm/yyyy otherwise you shouldn't convert it!

    2nd time it changes the date from mm/dd/yyyy to dd/mm//yyyy and displays it the way you want it

    3rd time it changes the date display of the estimated due date

    4th time it changes the date display of the estimated conception

    You can replace the <script> tags in the <head> with this or find and insert the four lines yourself. I have marked them. Here it is:

    <SCRIPT LANGUAGE="JavaScript">
    <!-- Original:  Ronnie T. Moore, Editor -->
    <!-- Web Site:  The JavaScript Source -->
    
    <!-- This script and many more are available free online at -->
    <!-- The JavaScript Source!! http://javascript.internet.com -->
    
    <!-- Begin
    function isValidDate(dateStr) {
    // Date validation function courtesty of 
    // Sandeep V. Tamhankar (stamhankar@hotmail.com) -->
    
    // Checks for the following valid date formats:
    // MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
    
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/; // requires 4 digit year
    
    var matchArray = dateStr.match(datePat); // is the format ok?
    if (matchArray == null) {
    alert("Date is not in a valid format.")
    return false;
    }
    month = matchArray[1]; // parse date into variables
    day = matchArray[3];
    year = matchArray[4];
    if (month < 1 || month > 12) { // check month range
    alert("Month must be between 1 and 12.");
    return false;
    }
    if (day < 1 || day > 31) {
    alert("Day must be between 1 and 31.");
    return false;
    }
    if ((month==4 || month==6 || month==9 || month==11) && day==31) {
    alert("Month "+month+" doesn't have 31 days!")
    return false;
    }
    if (month == 2) { // check for february 29th
    var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
    if (day>29 || (day==29 && !isleap)) {
    alert("February " + year + " doesn't have " + day + " days!");
    return false;
       }
    }
    return true;
    }
    
    function dispDate(dateObj) {
    month = dateObj.getMonth()+1;
    month = (month < 10) ? "0" + month : month;
    
    day   = dateObj.getDate();
    day = (day < 10) ? "0" + day : day;
    
    year  = dateObj.getYear();
    if (year < 2000) year += 1900;
    
    return (month + "/" + day + "/" + year);
    }
    
    function pregnancyCalc(pregform) {
    menstrual = new Date(); // creates new date objects
    ovulation = new Date();
    duedate = new Date();
    today = new Date();
    cycle = 0, luteal = 0; // sets variables to invalid state ==> 0
    
    //************************ F I R S T   C H A N G E ****************************************************
    pregform.menstrual.value = pregform.menstrual.value.replace(/(\d{2})\/(\d{2})\/(\d{4})/, "$2/$1/$3");
    //***************************************************** ***********************************************
    
    if (isValidDate(pregform.menstrual.value)) { // Validates menstual date 
    menstrualinput = new Date(pregform.menstrual.value);
    menstrual.setTime(menstrualinput.getTime())
    }
    else return false; // otherwise exits
    
    cycle = (pregform.cycle.value == "" ? 28 : pregform.cycle.value); // defaults to 28
    // validates cycle range, from 22 to 45
    if (pregform.cycle.value != "" && (pregform.cycle.value < 22 || pregform.cycle.value > 45)) {
    alert("Your cycle length is either too short or too long for \n"
    + "calculations to be very accurate!  We will still try to \n"
    + "complete the calculation with the figure you entered. ");
    }
    
    luteal = (pregform.luteal.value == "" ? 14 : pregform.luteal.value); // defaults to 14
    // validates luteal range, from 9 to 16
    if (pregform.luteal.value != "" && (pregform.luteal.value < 9 || pregform.luteal.value > 16)) {
    alert("Your luteal phase length is either too short or too long for \n"
    + "calculations to be very accurate!  We will still try to complete \n"
    + "the calculation with the figure you entered. ");
    }
    
    //************************ S E C O N D   C H A N G E **************************************************
    pregform.menstrual.value = pregform.menstrual.value.replace(/(\d{2})\/(\d{2})\/(\d{4})/, "$2/$1/$3");
    //***************************************************** ***********************************************
    
    // sets ovulation date to menstrual date + cycle days - luteal days
    // the '*86400000' is necessary because date objects track time
    // in milliseconds;  86400000 milliseconds equals one day
    ovulation.setTime(menstrual.getTime() + (cycle*86400000) - (luteal*86400000));
    pregform.conception.value = dispDate(ovulation);
    
    //************************ T H I R D     C H A N G E **************************************************
    pregform.conception.value = pregform.conception.value.replace(/(\d{2})\/(\d{2})\/(\d{4})/, "$2/$1/$3");
    //***************************************************** ***********************************************
    
    // sets due date to ovulation date plus 266 days
    duedate.setTime(ovulation.getTime() + 266*86400000);
    pregform.duedate.value = dispDate(duedate);
    
    //************************ F O U R T H     C H A N G E ************************************************
    pregform.duedate.value = pregform.duedate.value.replace(/(\d{2})\/(\d{2})\/(\d{4})/, "$2/$1/$3");
    //***************************************************** ***********************************************
    
    // sets fetal age to 14 + 266 (pregnancy time) - time left
    var fetalage = 14 + 266 - ((duedate - today) / 86400000);
    weeks = parseInt(fetalage / 7); // sets weeks to whole number of weeks
    days = Math.floor(fetalage % 7); // sets days to the whole number remainder
    
    // fetal age message, automatically includes 's' on week and day if necessary
    fetalage = weeks + " week" + (weeks > 1 ? "s" : "") + ", " + days + " days";
    pregform.fetalage.value = fetalage;
    
    return false; // form should never submit, returns false
    }
    //  End -->
    </script>
    Code (markup):
     
    gandalf117, Nov 26, 2009 IP
  7. miscsoft

    miscsoft Peon

    Messages:
    375
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #7
    in .net you can use the cultureinfo to change the shortdatepattern. a similar thing must be there in other language also.
     
    miscsoft, Nov 26, 2009 IP
  8. Amit Oxy

    Amit Oxy Guest

    Messages:
    19
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #8
    var date = "12/23/2009";
    var month = date.slice(0,2);
    var day = date.slice(3,5);
    var year = date.slice(6,10);
    var newdate = day + "/" + month + "/" + year
     
    Amit Oxy, Nov 28, 2009 IP
  9. Mastermaniac

    Mastermaniac Peon

    Messages:
    128
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #9
    A new solution xD! :p

    function getTodaysDate() {
        with($ = new Date()) main = getDate() + (a = arguments[0]) + getMonth() + a + getFullYear();
        return main;
    }
    Code (markup):
    Just mention the separator!

    Like
    
    alert(getTodaysDate("/"))
    Code (markup):
     
    Mastermaniac, Nov 29, 2009 IP
  10. myst_dg

    myst_dg Active Member

    Messages:
    224
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    58
    #10
    Split the original date string into three parts, and combine to another string in your desired order.
     
    myst_dg, Dec 2, 2009 IP
  11. camjohnson95

    camjohnson95 Active Member

    Messages:
    737
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #11
    What if someone enters 1/1/2009 ?

    Your probably better off, converting the date that the user inputted into MM/DD/YYYY format, perform your calculations, and convert back to DD/MM/YYYY when displaying the results. One way to convert.. something like:
    
    function swapdates(myDate) {
        var seperator = (myDate.search("/")) ? "/" : "-";
        var arrDate = myDate.split(seperator);
        myDate = arrDate[1] + "/" + arrDate[0] + "/" + arrDate[2];  
        return myDate;
    }
    
    Code (markup):
    this function should swap between the dates...
    e.g swapdates("12/31/2009") should return 31/12/2009
    and vice-versa. you can convert the string (when in mm/dd/yyyy format, to a date object by using:
    myNewDate = new Date(mydatestring);
     
    Last edited: Dec 3, 2009
    camjohnson95, Dec 3, 2009 IP
  12. MR. TODD

    MR. TODD Peon

    Messages:
    18
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #12
    gr8 thread
     
    MR. TODD, Dec 3, 2009 IP