javascript user value convert to format [duplicate]

元气小坏坏 提交于 2020-04-11 18:30:40

问题


    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...


回答1:


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'




回答2:


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;
}



回答3:


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'));


来源:https://stackoverflow.com/questions/41766693/javascript-user-value-convert-to-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!