Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Time validation in 24 hours format using regular expression with javascript

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 6.65k
    Comment on it

    In this blog we will learn to convert the time format as per requirement with the help of the regular expression.

     

    Pattern of regular expression for time in 24-hour format:

     

    1. Pattern 1: ( [01]?[0-9]|2[0-3] ) : [0-5][0-9]

     

    Explanation:

              (                      // beginning of the group

              [01]?[0-9]        // date may start with 0-9, 1-9, 00-09, 10-19

               |                    // or

               2[0-3]            // date may range between 20-23

               )                   // close of group

               :                   // followed by a semi colon

               [0-5][0-9]      // further followed by 0..5 and 0..9, i.e, 00 to 59

     

    2. Pattern 2: (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/)

     

    above mentioned patterns fulfills the following requirements:

    • Time is always expressed in 24 hour and of HH:MM format
    • String must have at least one timerange or many which should be separated by comma
    • Any spaces between the time elements should be tolerated by the matching pattern.
    • String validated must match completely.

     

    Following is the sample code to convert the format:

     

    function tConvert (time) {
    
    	// Check correct time format and split into components
    
    	time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
    
    	if (time.length > 1) { 		// If time format correct
    
    		time = time.slice (1);  	// Remove full string match value
    
    		time[5] = +time[0] < 12 ? 'AM' : 'PM'; 	// Set AM/PM
    
    		time[0] = +time[0] % 12 || 12;	 // Adjust hours
    
    	}
    
    	return time.join (''); // return adjusted time or original string
    
    }
    

     

    Hope you find this blog useful!

    Happy Coding :)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: