jquery convert time from english to french

时间:2015-10-30 23:50:41

标签: javascript jquery

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

1 个答案:

答案 0 :(得分:1)

也许是这样的:

&#13;
&#13;
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);
  }
&#13;
<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>
&#13;
&#13;
&#13;

正则表达式仅匹配数字(\d)和冒号后跟PM(前导空格)。然后将每个匹配分割为:,并将12添加到第一个分割(以产生24小时时钟)。