How to format datestring to d, MMM yyyy in javascript

匿名 (未验证) 提交于 2019-12-03 09:58:14

问题:

I got this:

function parseDate(s) { var d = s.split(/\D/);   return new Date(d[2], --d[1], d[0]); 

with the calendar tag like this:

<p:calendar id="testDate" styleClass="calendar" pattern="d MMM, yyyy" maxlength="10" onchange="$(this).val(parseDate($(this).val()))" onfocus="$(this).mask('99/99/9999');" > <p:watermark for="testDate" value="mm/dd/yyyy" /> </p:calendar> 

I need to manually parse a date from 'dd/mm/yyyy' to 'd, MMM yyyy' but with the function above the result is e.g. "Wed, Aug 09 1995 00:00:00" hence could someone help me and tell how how i could change the format so that the string produced would be d, MMM yyyy?

I know this should be a very basic task however i am still learning how to code better, therefore all your help and explanations are greatly appreciated!

回答1:

Lazy method: use the .toString()

function parseMyDate(s){      var dateParts = s.split("/");      var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);      var dateStrParts = date.toString().split(" ");      return (date.getDate() + ", " + dateStrParts[1] + " " + dateStrParts[3]); }  console.log(parseMyDate("09/06/2014")); 

JSFiddle Demo



回答2:

Take a look at momentjs you can use it to parse your date and format it into whatever format you'd like.



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