我有一个日期,格式是2014年5月11日太阳。如何使用JavaScript将其转换为2014-05-11 ?

函数taskDate(dateMilli) { var d = (new Date(dateMilli) + ")。分割(' '); D [2] = D [2] + ','; 返回[d[0], d[1], d[2], d[3]]。加入(' '); } var datemilli =日期。解析(' 2014年5月11日'); console.log (taskDate (datemilli));

上面的代码给了我相同的日期格式,2014年5月11日。我该如何解决这个问题?


当前回答

我用这种方式获取日期格式为yyyy-mm-dd:)

var todayDate =新日期。slice (0) (10); 游戏机。log (todayDate);

其他回答

检索年、月和日,然后将它们组合在一起。直接、简单、准确。

函数formatDate(日期){ var year = date.getFullYear().toString(); var month = (date.getMonth() + 101).toString().substring(1); var day = (date.getDate() + 100).toString().substring(1); 返回年+“-”+月+“-”+日; } / /使用例子: 警报(formatDate(新日期()));

将日期转换为yyyy-mm-dd格式的最简单方法是这样做:

var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
                    .toISOString()
                    .split("T")[0];

工作原理:

new Date("Sun May 11,2014") converts the string "Sun May 11,2014" to a date object that represents the time Sun May 11 2014 00:00:00 in a timezone based on current locale (host system settings) new Date(date.getTime() - (date.getTimezoneOffset() * 60000 )) converts your date to a date object that corresponds with the time Sun May 11 2014 00:00:00 in UTC (standard time) by subtracting the time zone offset .toISOString() converts the date object to an ISO 8601 string 2014-05-11T00:00:00.000Z .split("T") splits the string to array ["2014-05-11", "00:00:00.000Z"] [0] takes the first element of that array


Demo

var date =新日期(“太阳5月11日”); var dateString =新日期(日期。 toISOString()。 斯普利特(“T”)[0]; 游戏机。log (dateString);

注意:

The first part of the code (new Date(...)) may need to be tweaked a bit if your input format is different from that of the OP. As mikeypie pointed out in the comments, if the date string is already in the expected output format and the local timezone is west of UTC, then new Date('2022-05-18') results in 2022-05-17. And a user's locale (eg. MM/DD/YYYY vs DD-MM-YYYY) may also impact how a date is parsed by new Date(...). So do some proper testing if you want to use this code for different input formats.

如果你不反对使用库,你可以像这样使用Moments.js库:

var now = new Date(); var date弦=当下。 瓦尔·戴斯特时刻。格式(“YYYY-MM-DD HH: mm: ss”); <剧本剧本src = " https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js " > < / >

这对我来说很有效,如果需要测试,你可以直接将它粘贴到你的HTML中:

<script type="text/javascript">
    if (datefield.type!="date"){ // If the browser doesn't support input type="date",
                                 // initialize date picker widget:
        jQuery(function($){ // On document.ready
            $('#Date').datepicker({
                dateFormat: 'yy-mm-dd', // THIS IS THE IMPORTANT PART!!!
                showOtherMonths: true,
                selectOtherMonths: true,
                changeMonth: true,
                minDate: '2016-10-19',
                maxDate: '2016-11-03'
            });
        })
    }
</script>

我建议使用类似formatDate-js的东西,而不是每次都试图复制它。只需使用一个支持所有主要strftime操作的库。

new Date().format("%Y-%m-%d")