www.webdeveloper.com
Results 1 to 2 of 2

Thread: More efficient way to do this?

  1. #1
    Join Date
    Sep 2008
    Posts
    104

    More efficient way to do this?

    This code works perfectly, but tere has to be a more efficient way to do this. The comments should make sense of it so you know what I'm doing. I had to comment that crap out of it to keep everything in mind when writing it.

    Code:
    // ex. aa = '9/2/2009 8:31:12 PM'
    if (aa.indexOf("pm")!=-1)
    		{
    			timestamp = aa.split(" ")
    			
    			// sets time = 8:31:12
    			time = timestamp[1] 
    			
    			hr = time.split(":")
    			
    			//sets militaryTime = 8
    			militaryTime= hr[0] 
    			
    			//converts to militaryTime. 8 becomes 20
    			militaryTime= parseInt(militaryTime) + 12;  
    			
    			//puts timestamp back together using military instead of conventional
    			sortableStamp= timestamp[0] + " " + militaryTime + ":" + hr[1] + ":" + hr[2] 
    			
    			// aa = 9/2/2009 20:31:12
    			aa = sortableStamp  
    		}
                              // ex. aa = '9/2/2009 8:31:12 AM'
    		if (aa.indexOf("am")!=-1)
    		{
    			timestamp = aa.split(" ");
    			
    			// sets time = 8:31:12
    			time = timestamp[1];
    			
    			hr = time.split(":");
    			
    			//sets militaryTime = 8			
    			militaryTime= hr[0];
    			
    			// if single digit hour, pad w/ a 0 or sort won't work
    			if (militaryTime.length == 1)
    			{
    				sortableStamp=timestamp[0] + " 0" + militaryTime + ":" + hr[1] + ":" + hr[2];
    			}
    			else
    			{
    				sortableStamp=timestamp[0] + " " + militaryTime + ":" + hr[1] + ":" + hr[2];
    			}
    			//sets aa = '9/2/2009 08:31:12'
    			aa = sortableStamp;
    		}

  2. #2
    Join Date
    Dec 2002
    Location
    Pleasanton, CA
    Posts
    2,132
    When you find yourself repeating the same code, if(..pm){} and if(..am){}, look for a possibility to combine (or create a subroutine)
    Just for fun....
    Code:
    var aa = '9/2/2009 8:31:12 AM';
    
    var timestamp = aa.split(' ');
    var hms = timestamp[1].split(':');
    if (/PM/.test(timestamp[2])) { hms[0] = Number(hms[0]) + 12; }
    if (hms[0]<10) { hms[0] = '0'+hms[0]; }
    aa = timestamp[0]+' '+hms.join(':');  
    
    alert(aa);
    PS: You should probably think about padding all single digits in both date and time.
    A opportunity for a sub...
    Last edited by Nedals; 09-04-2009 at 08:34 PM. Reason: Add comment

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles