我有一个日期,格式是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日。我该如何解决这个问题?


当前回答

toISOString()假设日期是本地时间并将其转换为UTC。您将得到一个不正确的日期字符串。

下面的方法应该返回您需要的内容。

Date.prototype.yyyymmdd = function() {         

    var yyyy = this.getFullYear().toString();                                    
    var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based         
    var dd  = this.getDate().toString();             

    return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};

来源:https://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/

其他回答

不幸的是,JavaScript的Date对象有很多陷阱。任何基于Date内置toISOString的解决方案都必须打乱时区,这一点在这个问题的其他一些答案中已经讨论过。表示ISO-8601日期(没有时间)的干净解决方案是由Temporal提供的。来自Temporal提案的PlainDate。从2021年2月起,你必须选择最适合你的变通方法。

使用日期与香草字符串连接

假设您的内部表示基于Date,您可以手动执行字符串连接。下面的代码避免了Date的一些缺陷(时区、从零开始的月份、缺少2位数格式),但可能还存在其他问题。

function vanillaToDateOnlyIso8601() {
  // month May has zero-based index 4
  const date = new Date(2014, 4, 11);

  const yyyy = date.getFullYear();
  const mm = String(date.getMonth() + 1).padStart(2, "0"); // month is zero-based
  const dd = String(date.getDate()).padStart(2, "0");

  if (yyyy < 1583) {
    // TODO: decide how to support dates before 1583
    throw new Error(`dates before year 1583 are not supported`);
  }

  const formatted = `${yyyy}-${mm}-${dd}`;
  console.log("vanilla", formatted);
}

使用Date和helper库(例如formatISO from Date -fns)

这是一种流行的方法,但您仍然被迫将日历日期作为date来处理,它表示

一个独立于平台格式的单一时刻

下面的代码应该可以完成这项工作:

import { formatISO } from "date-fns";

function dateFnsToDateOnlyIso8601() {
  // month May has zero-based index 4
  const date = new Date(2014, 4, 11);
  const formatted = formatISO(date, { representation: "date" });
  console.log("date-fns", formatted);
}

找到一个正确表示日期和时间的库

我希望有一个干净的、经过实战考验的库,它能带来自己设计良好的日期-时间表示。对于这个问题中的任务,一个很有希望的候选者是@js-joda/core中的LocalDate,但是这个库不如date-fns活跃。在处理一些示例代码时,在添加可选的@js-joda/timezone后,我也遇到了一些问题。

然而,核心功能在我看来非常干净:

import { LocalDate, Month } from "@js-joda/core";

function jodaDateOnlyIso8601() {
  const someDay = LocalDate.of(2014, Month.MAY, 11);
  const formatted = someDay.toString();
  console.log("joda", formatted);
}

用时间提案填充实验

不建议在生产环境中使用,但是如果你愿意,你可以导入future:

import { Temporal } from "proposal-temporal";

function temporalDateOnlyIso8601() {
  // yep, month is one-based here (as of Feb 2021)
  const plainDate = new Temporal.PlainDate(2014, 5, 11);
  const formatted = plainDate.toString();
  console.log("proposal-temporal", formatted);
}

这对我来说很有效,如果需要测试,你可以直接将它粘贴到你的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>
format = function date2str(x, y) {
    var z = {
        M: x.getMonth() + 1,
        d: x.getDate(),
        h: x.getHours(),
        m: x.getMinutes(),
        s: x.getSeconds()
    };
    y = y.replace(/(M+|d+|h+|m+|s+)/g, function(v) {
        return ((v.length > 1 ? "0" : "") + z[v.slice(-1)]).slice(-2)
    });

    return y.replace(/(y+)/g, function(v) {
        return x.getFullYear().toString().slice(-v.length)
    });
}

结果:

format(new Date('Sun May 11,2014'), 'yyyy-MM-dd')
"2014-05-11

之前的一些答案是可以的,但是不是很灵活。我想要一些能够真正处理更多边缘情况的东西,所以我采用了@orangleliu的答案并扩展了它。https://jsfiddle.net/8904cmLd/1/

function DateToString(inDate, formatString) {
    // Written by m1m1k 2018-04-05

    // Validate that we're working with a date
    if(!isValidDate(inDate))
    {
        inDate = new Date(inDate);
    }

    // See the jsFiddle for extra code to be able to use DateToString('Sun May 11,2014', 'USA');
    //formatString = CountryCodeToDateFormat(formatString);

    var dateObject = {
        M: inDate.getMonth() + 1,
        d: inDate.getDate(),
        D: inDate.getDate(),
        h: inDate.getHours(),
        m: inDate.getMinutes(),
        s: inDate.getSeconds(),
        y: inDate.getFullYear(),
        Y: inDate.getFullYear()
    };

    // Build Regex Dynamically based on the list above.
    // It should end up with something like this: "/([Yy]+|M+|[Dd]+|h+|m+|s+)/g"
    var dateMatchRegex = joinObj(dateObject, "+|") + "+";
    var regEx = new RegExp(dateMatchRegex,"g");
    formatString = formatString.replace(regEx, function(formatToken) {
        var datePartValue = dateObject[formatToken.slice(-1)];
        var tokenLength = formatToken.length;

        // A conflict exists between specifying 'd' for no zero pad -> expand
        // to '10' and specifying yy for just two year digits '01' instead
        // of '2001'.  One expands, the other contracts.
        //
        // So Constrict Years but Expand All Else
        if (formatToken.indexOf('y') < 0 && formatToken.indexOf('Y') < 0)
        {
            // Expand single digit format token 'd' to
            // multi digit value '10' when needed
            var tokenLength = Math.max(formatToken.length, datePartValue.toString().length);
        }
        var zeroPad = (datePartValue.toString().length < formatToken.length ? "0".repeat(tokenLength) : "");
        return (zeroPad + datePartValue).slice(-tokenLength);
    });

    return formatString;
}

使用示例:

DateToString('Sun May 11,2014', 'MM/DD/yy');
DateToString('Sun May 11,2014', 'yyyy.MM.dd');
DateToString(new Date('Sun Dec 11,2014'),'yy-M-d');

Date.js很适合这个。

require("datejs")
(new Date()).toString("yyyy-MM-dd")