我有一个日期,格式是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/

其他回答

之前的一些答案是可以的,但是不是很灵活。我想要一些能够真正处理更多边缘情况的东西,所以我采用了@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');
formatDate(date) {
  const d = new Date(date)
  const ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d);
  const mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(d);
  const da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d);
  return `${da}-${mo}-${ye}`;
}

console.log("Formatated Date : ", formatDate("09/25/2020") )
// Output :: Formatated Date : 25-Sep-2020
new Date('Tue Nov 01 2022 22:14:53 GMT-0300').toLocaleDateString('en-CA');

new Date().toLocaleDateString('pt-br').split( '/' ).reverse( ).join( '-' );

or

new Date().toISOString().split('T')[0]
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString()
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString().split('T')[0]

试试这个!

将日期转换为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.

这些答案没有一个让我很满意。我想要一个跨平台的解决方案,让我可以在不使用任何外部库的情况下使用本地时区的一天。

这是我想到的:

function localDay(time) {
  var minutesOffset = time.getTimezoneOffset()
  var millisecondsOffset = minutesOffset*60*1000
  var local = new Date(time - millisecondsOffset)
  return local.toISOString().substr(0, 10)
}

它应该在日期引用的时区中以YYYY-MM-DD格式返回日期的日期。

因此,例如,localDay(new Date("2017-08-24T03:29:22.099Z"))将返回"2017-08-23",即使它在UTC已经是24日。

你需要填充Date.prototype.toISOString,它才能在Internet Explorer 8中工作,但它应该在其他任何地方都能得到支持。