Web Analytics Made Easy -
StatCounter Time converter in Java script- string to string - CodingForum

Announcement

Collapse
No announcement yet.

Time converter in Java script- string to string

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Time converter in Java script- string to string

    Hello Guys,
    its me again on my journey to Im trying to make a function that converts string from 24 hour format into string 12 h format. Test : string "01:10"should return"01:10a.m.",
    12:20p.m."-->"12:20" ,
    "11:59p.m." --> "23:59" string etc.

    Code:
      function timeConvert (time) {
       time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
    
        if (time.length > 1) { 
          time = time.slice (1); 
          time[5] = +time[0] < 12 ? 'AM' : 'PM';
          time[0] = +time[0] % 12 || 12; 
        }
        return time.join ('');
      }

  • #2
    You haven't told us what your problem is.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

    Comment


    • #3
      Hello Guys,
      its me again on my journey to Im trying to make a function that converts string from 24 hour format into string 12 h format. Test : string "01:10"should return"01:10a.m.",
      The next two lines make no sense; they're converting 12 hour clock to 24 hour:
      12:20p.m."-->"12:20" ,
      "11:59p.m." --> "23:59" string etc

      Not what you asked for.

      Try this:
      Code:
      <script>
      function timeConvert (time) {
          var h = time.split(":");
      	var b = Number(h.shift());
      	var hr = ((b + 11) % 12 + 1);
      	var stuff = b >= 12 ? "PM":"AM";
      	var out = hr + ":" + h.pop() + stuff;
      	alert(out);
      }
      timeConvert("23:10");
      </script>
      Evolution - The non-random survival of random variants.
      Physics is actually atoms trying to understand themselves.

      Comment


      • #4
        The OP required that string "01:10"should return"01:10a.m."

        So an additional line of code is needed.

        var stuff = b >= 12 ? "PM":"AM";
        if (hr <10) {hr = "0" + hr}

        All the code given in this post has been tested and is intended to address the question asked.
        Unless stated otherwise it is not just a demonstration.

        Comment

        Working...
        X