-1

example: if i have this string or number 020117 first two numbers are the day, first four numbers are day and month, full text are day, month and year.

How can I make this happen 020117 -> 02/01/2017.

Please, I need your help

Pat
  • 2,540
  • 1
  • 21
  • 28
  • 1
    Do you just want to reformat the text, or get a Date object? Either way, 2 or 3 lines of code will do the trick. What have you tried? – RobG Jan 04 '17 at 00:09
  • Possible duplicate of [Converting string to date in js](http://stackoverflow.com/questions/5619202/converting-string-to-date-in-js) – ameed Jan 04 '17 at 02:21

2 Answers2

0
<?php

$s = "020117";
print substr($s, 0, 2)."/".substr($s, 2, 2)."/20".substr($s, 4, 2);
?>

or as function:

<?php


function itd($i){
 return substr($i, 0, 2)."/".substr($i, 2, 2)."/20".substr($i, 4, 2);
}

print itd('020117');
?>
Eugen
  • 1,356
  • 12
  • 15
0

You can convert it to a Date with a simple function like:

function parseDMY(s) {
  // Get date parts
  var b = s.match(/\d\d/g);
  var d;
  
  // If got 3 parts, convert to Date
  if (b && b.length == 3) {
    d = new Date('20' + b[2], --b[1], b[0]);
    //Check date values were valid, if not set to invalid date
    d = d && d.getMonth() == b[1]? d : new Date(NaN);
  }
  return d;     
}

// Basic support
console.log(parseDMY('020117').toString());

// New support for toLocaleString
console.log(parseDMY('020117').toLocaleDateString('en-GB'));

Or just reformat the string:

var s = '020117';
console.log(s.replace(/(\d\d)(\d\d)(\d\d)/, '$1/$2/20$3'))
RobG
  • 142,382
  • 31
  • 172
  • 209