0
    var t = "Jan. 20, 2017 20:28:53"
    var s = t.format("%m/%d/%Y %H:%M:%S");
    alert(s);

How I convert the value into the

01/20/2017 20:28:53

this format.Please help me. Thank you...

RobG
  • 142,382
  • 31
  • 172
  • 209
bob marti
  • 1,523
  • 3
  • 11
  • 27

3 Answers3

0

Try the moment library http://momentjs.com/

You can do

moment('Jan. 20, 2017 20:28:53').format('MM/DD/YYYY HH:mm:ss')

returns -> '01/20/2017 20:28:53 PM'

williamcabrera4
  • 270
  • 2
  • 12
  • thanks for your answer.but i can't implement the project with momentjs library function – bob marti Jan 20 '17 at 15:16
  • Using a parser, you should also provide the format of the string, otherwise you're letting the parser guess. – RobG Jan 20 '17 at 21:28
0

Try this

var t = "Jan. 20, 2017 20:28:53"

var test = new Date(t);

var str = [addTrailingZero(test.getMonth()+1), addTrailingZero(test.getDate()+1),test.getFullYear()].join('/')
+ ' ' +
[addTrailingZero(test.getHours()+1), addTrailingZero(test.getMinutes()+1),
addTrailingZero(test.getSeconds()+1)
].join(':');

alert(str);

function addTrailingZero(date) {
    if ( date < 10 ) {
    return '0' + date;
  }

  return date;
}
0

Parsing strings with the Date constructor (or Date.parse, they are equivalent for parsing) is not recommended due to the many differences between implementations. Parsing of a string in a format like 'Jan. 20, 2017 20:28:53' is implementation dependent and may result in an invalid date.

If you want to create a Date from a string, use a bespoke function or a library, there are plenty to choose from.

But you don't need to create a Date to reformat a date string, you can just reformat the string:

function reformatDatestring(s) {
  function z(n) {return (n<10?'0':'') + n}
  var months = 'jan feb mar apr may jun jul aug sep oct nov dec'.split(' ');
  var b = s.split(/[\.,]?\s/);
  var month = months.indexOf(b[0].toLowerCase());
  return z(month+1) + '/' + z(b[1]) + '/' + b[2] + ' ' + b[3];
}

console.log(reformatDatestring('Jan. 20, 2017 20:28:53'));
RobG
  • 142,382
  • 31
  • 172
  • 209