英文:
Join year, month and day strings to form a date in format YYYY-MM-DD with moment
问题
var year = "2023";
var month = "10";
var day = "20";
var date = new moment(
year + month + day, "YYYY-MM-DD"
);
console.log(date);
奇怪的是,它返回的不是 "2023-10-20",而是 "1643950800000",我不太了解momentJS。
英文:
In my application a user enters a year, a month and a day separately. I'm simply trying to display what they entered back to them for confirmation but I'd like to use moment instead of concatenating strings.
var year = "2023";
var month = "10";
var day = "20";
var date = new moment(
year + month + day, "YYYY-MM-DD"
);
console.log(date);
Strangely instead of returning "2023-10-20", it returns "1643950800000" and I'm not sure why. I'm not very familiar with momentJS.
Thanks
答案1
得分: 2
你可以通过在 object
中指定一些单位来创建一个时刻。
演示:
var year = "2023";
var month = "10";
var day = "20";
var date = moment({
year: year,
month: month - 1, // 月份从零开始计数
day: day
});
console.log(date.format("YYYY-MM-DD"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
英文:
You can create a moment by specifying some of the units in an object
.
Demo:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var year = "2023";
var month = "10";
var day = "20";
var date = moment({
year: year,
month: month - 1, //months are zero-indexed
day: day
});
console.log(date.format("YYYY-MM-DD"));
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
<!-- end snippet -->
答案2
得分: 1
这部分内容的翻译如下:
我查看了文档(是的,我本应该先去那里,抱歉)。
这个代码可以工作:
var date = new moment(
year + month + day, "YYYYMMDD"
).format("YYYY-MM-DD")
英文:
I had a look at the docs (yes I should have gone there first, apologies).
This works:
var date = new moment(
year + month + day, "YYYYMMDD"
).format("YYYY-MM-DD")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论