0

I need to change all the time on my site from english to french ie 7:15 pm = 19 h 15. I do not have access to back end to change the time format. so I am using indexOf and .replace. It works but only for the first PM in the p how can i loop them. here is the code so far.

<script>
function myFunction() {

 var str = "12:00 AM test text at 9:10 PM this se second 6:00 PM doe not works.";


var matchs = str.match(/PM/gi); //can be used for loop amount 

var n = str.indexOf("PM")-6; //first digit before pm
var n2 = str.indexOf("PM")-5; //second digit before pm
var res = str.charAt(n) + str.charAt(n2);// add together

var myInteger = parseInt(res)+12;// make it ind and add 12

var str1= str.replace(res ,' '+myInteger).replace('PM','').replace(/PM/g,'').replace(/:/g,' h ').replace(/00/g,' ').replace('AM','');// replace 
 alert(str1);
 document.getElementById("demo").innerHTML = str1
}

thanks

  • Possible duplicate of [Convert date to another timezone in JavaScript](http://stackoverflow.com/questions/10087819/convert-date-to-another-timezone-in-javascript) – kemicofa ghost Oct 31 '15 at 00:03

1 Answers1

1

Maybe like this:

var str = $('#time').text();

var t = str.match(/[\d:]+(?= PM)/g);
for (var i = 0; i < t.length; i++) {
  var match = t[i].split(':');
  var th = +match[0] + 12 + ' h';
  var tm = ' ' + match[1];
  var ft = th + tm;
  var str = str.replace(t[i], ft).replace(/PM/g, '');
  $('#time').html(str);
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "time">12:00 AM test text at 9:10 PM this se second 6:00 PM doe not works.</div>

The regex matches numbers (\d) and the colon only if followed by PM (leading space). Each match is then split on : and 12 added to the first split (to make a 24hr clock).

sideroxylon
  • 4,338
  • 1
  • 22
  • 40