问题
I am using Moment.js format function on a current date as
var startDate = moment(new Date()).format('MM/DD/YY');
The result is 06/28/20
What happens is that it retains only the year part: 20 as "06/28/20", after I used new Date(startDate)
, the result is "Mon Jun 28 1920 00:00:00 GMT+0530 (India Standard Time)".
After this when I applied another format on "06/28/20":
startDate = moment(startDate ).format('MM-DD-YYYY');
The result is 06-28-1920
In Google Chrome and Firefox it gives the correct date for the second attempt as: 06-28-2020.
My code is:
$(document).ready(function() {
var startDate = moment(new Date()).format('MM/DD/YY');
alert("startDate ==="+startDate +"==="+new Date(startDate ));
startDate = moment(startDate ).format('MM-DD-YYYY');
alert("startDate ==="+startDate +"==="+new Date(startDate ));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
回答1:
Please find the below snippet , which might help you
$(document).ready(function() {
var startDate = moment(new Date()).format('MM/DD/YY');
alert("startDate ==="+startDate +"==="+new Date(startDate ));
startDate = moment(new Date(startDate)).format('MM-DD-YYYY');
var str="06-28-2020";
alert("startDate ==="+startDate +"==="+new Date(str.replaceAll("-","/")));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
回答2:
If you are using Moment, use Moment only. Parsing date strings with Date.parse()
or new Date(
) (same thing under hood) is not recommended.
Your approach should be using moment(DATE, "DD/MM/YY")
which handles the 2k year problem you face, automatically.
来源:https://stackoverflow.com/questions/62622534/date-went-wrong-when-using-momentjs-date-format-in-ie-11