简体   繁体   中英

Moment.js formatting “Date(2021,0,1)”

I'm working with moment.js and need help converting the following string:

let dtString = "Date(2021,0,1)";
let dt = moment(dtString, 'YYYY,M,D').format('l');

"Date(2021,0,1)" has a zero based month. The code above returns invalid date.

When I try "Date(2021,1,1)" , dt returns 1/1/2021.

How can I get moment to recognize that the M value is a zero based month and return "Date(2021,0,1)" as 1/1/2021?

UPDATE:
Here's something else I just tried...again it's clunky but works.

 let dtString = "Date(2021,0,1)"; let dtArray = dtString.replace("Date(", "").replace(")", "").split(",").map(Number); let jsDate = new Date(dtArray[0], dtArray[1], dtArray[2]); let dt = moment(jsDate).format('l'); console.log(dt);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

UPDATE 2:
Combining @kometen and @eskew I've found that this also works. Thank you to both!

 let dtString = "Date(2021,0,1)"; let dtArray = dtString.replace("Date(", "").replace(")", "").split(",").map(Number); let dt = moment(dtArray).format('l'); console.log(dt);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Looks like moment().month() does accept 0-based month-numbering so if you change it to moment([2012, 0, 31]) it should work.

One slightly clunky way of doing this would be to parse dtString into its parts and then reassemble them in the moment() constructor's parameter in an array structure , which will tell momentjs to parse them in the same way the native Date API would (including zero-indexed month values, among others):

 let dtString = "Date(2021,0,1)"; let dtStringFormat = /Date\((?<Year>\d{4}),(?<Month>\d{1,2}),(?<Day>\d{1,2})\)/g; let groups = dtStringFormat.exec(dtString).groups; let dt = moment(Object.values(groups)); console.dir(dt);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>

Disclaimer. I neither recommend or endorse using eval as it can be abused.

Having said that, if you can trust the date string is not going to include anything dangerous than you could use it like so. No parsing required.

 let dtString = "Date(2021,0,1)"; let date = eval('new ' + dtString); let dt = moment(date).format('l'); document.getElementById('date').innerText = dt;
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script> <div id="date"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM