0

I am using angular UI date picker to get the date. I save the date into a string variable. The problem is that I want the date to be trimmed out in a very specific format. I don't know regex, at all which I think is the right way to do this in javascript? Can somebody tell me the regex that I can write in a function that will trim the input to the specific output using native javascript only. e.g. Input:

Thursday sep 20-2-2015 00:00:00 GMT (+5:00) Pakistan Standard Time.

Output should be:

20-2-2015 00:00:00.

Thanks a lot!

Dmytro Hutsuliak
  • 1,741
  • 4
  • 21
  • 37
Ahsan Abbas
  • 73
  • 1
  • 8
  • I think you do not need regex for this, did you try giving a look to this: http://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date – XOR-Manik Sep 22 '15 at 19:10
  • The example uses the getDate method which i believe gets the current date only? what about if i chose the date randomly using a date picker then i dont this would work? Also it doesn't answers about the time hh:mm:ss that i want too. Or maybe i have missed something on that link? – Ahsan Abbas Sep 22 '15 at 19:19

2 Answers2

1
<html>
  <body>
    <script language=javascript>
      var txt='Thursday sep 20-2-2015 00:00:00 GMT (+5:00) Pakistan Standard Time';

      var re1='.*?';  // Non-greedy match on filler
      var re2='(20-2-2015)';  // DDMMYYYY 1
      var re3='(\\s+)'; // White Space 1
      var re4='(00:00:00)'; // HourMinuteSec 1

      var p = new RegExp(re1+re2+re3+re4,["i"]);
      var m = p.exec(txt);
      if (m != null)
      {
          var ddmmyyyy1=m[1];
          var ws1=m[2];
          var time1=m[3];
          document.write("("+ddmmyyyy1.replace(/</,"&lt;")+")"+"("+ws1.replace(/</,"&lt;")+")"+"("+time1.replace(/</,"&lt;")+")"+"\n");
      }
    </script>
  </body>
</html>
OlivierBlanvillain
  • 7,701
  • 4
  • 32
  • 51
1

This should give you what you want:

var date = "Thursday sep 20-2-2015 00:00:00 GMT (+5:00) Pakistan Standard Time";
var expectedDate = date.match(/\d{1,2}-\d{1,2}-\d{4}\s\d{2}:\d{2}:\d{2}/g);
James Jithin
  • 10,183
  • 5
  • 36
  • 51
  • Thanks alot!! If it doesn't trouble can you please explain a lil bit what does the expression do? i mean how it is trimming? Thanks. – Ahsan Abbas Sep 22 '15 at 19:28
  • @AhsanAbbas, here we are not trimming. We are finding the match with our expression. `\d` is for digits `[0-9]`. `\d{1,2}` says occurrence of digits, minimum 1, maximum 2. Then you have `-` symbols as in the string. `\s` is for white-space. `\d{4}` says, match exactly 4 occurrence. And the `/g` at last is for global matching. – James Jithin Sep 22 '15 at 19:36