Join year, month and day strings to form a date in format YYYY-MM-DD with moment

huangapple go评论64阅读模式
英文:

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 = &quot;2023&quot;;
var month = &quot;10&quot;;
var day = &quot;20&quot;;

var date = moment({
  year: year,
  month: month - 1, //months are zero-indexed
  day: day
});
console.log(date.format(&quot;YYYY-MM-DD&quot;));

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js&quot;&gt;&lt;/script&gt;

<!-- 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, &quot;YYYYMMDD&quot;
).format(&quot;YYYY-MM-DD&quot;)

huangapple
  • 本文由 发表于 2023年7月10日 18:31:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76652880.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定