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


当前回答

之前的一些答案是可以的,但是不是很灵活。我想要一些能够真正处理更多边缘情况的东西,所以我采用了@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');

其他回答

PHP兼容的日期格式

下面是一个小函数,它可以接受与PHP函数date()相同的参数,并在JavaScript中返回日期/时间字符串。

注意,并不是PHP中的所有date()格式选项都受支持。您可以扩展parts对象来创建缺少的格式令牌

/** * Date formatter with PHP "date()"-compatible format syntax. */ const formatDate = (format, date) => { if (!format) { format = 'Y-m-d' } if (!date) { date = new Date() } const parts = { Y: date.getFullYear().toString(), y: ('00' + (date.getYear() - 100)).toString().slice(-2), m: ('0' + (date.getMonth() + 1)).toString().slice(-2), n: (date.getMonth() + 1).toString(), d: ('0' + date.getDate()).toString().slice(-2), j: date.getDate().toString(), H: ('0' + date.getHours()).toString().slice(-2), G: date.getHours().toString(), i: ('0' + date.getMinutes()).toString().slice(-2), s: ('0' + date.getSeconds()).toString().slice(-2) } const modifiers = Object.keys(parts).join('') const reDate = new RegExp('(?<!\\\\)[' + modifiers + ']', 'g') const reEscape = new RegExp('\\\\([' + modifiers + '])', 'g') return format .replace(reDate, $0 => parts[$0]) .replace(reEscape, ($0, $1) => $1) } // ----- EXAMPLES ----- console.log( formatDate() ); // "2019-05-21" console.log( formatDate('H:i:s') ); // "16:21:32" console.log( formatDate('Y-m-d, o\\n H:i:s') ); // "2019-05-21, on 16:21:32" console.log( formatDate('Y-m-d', new Date(2000000000000)) ); // "2033-05-18"

Gist

以下是formatDate()函数的更新版本和其他示例的要点:https://gist.github.com/stracker-phil/c7b68ea0b1d5bbb97af0a6a3dc66e0d9

重新格式化日期字符串是相当简单的,例如。

var s = ' 2014年5月11日'; 函数reformatDate(s) { 函数z(n){return ('0' + n).slice(-2)} var月=[‘简’,2月,3月,4月,“可能”,“君”, 7月,8月,9月,10月,11月,12月的]; var b = s.split(/\W+/); 返回b[3] + '-' + z (months.indexOf (b [1] .substr .toLowerCase (0, 3) ())) + '-' + z (b [2]); } console.log (reformatDate (s));

如果你不反对使用库,你可以像这样使用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 " > < / >

const today = new Date(); // or whatever const yearFirstFormater = (date): string => { const modifiedDate = new Date(date).toISOString().slice(0, 10); return `${modifiedDate.split('-')[0]}/${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[2]}`; } const monthFirstFormater = (date): string => { const modifiedDate = new Date(date).toISOString().slice(0, 10); return `${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[2]}/${modifiedDate.split('-')[0]}`; } const dayFirstFormater = (date): string => { const modifiedDate = new Date(date).toISOString().slice(0, 10); return `${modifiedDate.split('-')[2]}/${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[0]}`; } console.log(yearFirstFormater(today)); console.log(monthFirstFormater(today)); console.log(dayFirstFormater(today));

如果日期需要在所有时区都相同,例如表示数据库中的某个值,那么请确保在JavaScript date对象上使用UTC版本的日、月、年函数,因为这将以UTC时间显示,并避免在某些时区出现差一的错误。

更好的是,使用Moment.js日期库来进行这种格式设置。