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


当前回答

这段代码改变了DD MM YYYY的顺序

function convertDate(format, date) {
    let formatArray = format.split('/');
    if (formatArray.length != 3) {
        console.error('Use a valid Date format');
        return;
    }
    function getType(type) { return type == 'DD' ? d.getDate() : type == 'MM' ? d.getMonth() + 1 : type == 'YYYY' && d.getFullYear(); }
    function pad(s) { return (s < 10) ? '0' + s : s; }
    var d = new Date(date);
    return [pad(getType(formatArray[0])), pad(getType(formatArray[1])), getType(formatArray[2])].join('/');
}

其他回答

2021年的解决方案使用Intl。

现在所有浏览器都支持新的Intl对象。 您可以通过选择使用所需格式的“区域设置”来选择格式。

瑞典语言环境使用的格式是"yyyy-mm-dd":

// Create a date
const date = new Date(2021, 10, 28);

// Create a formatter using the "sv-SE" locale
const dateFormatter = Intl.DateTimeFormat('sv-SE');

// Use the formatter to format the date
console.log(dateFormatter.format(date)); // "2021-11-28"

使用Intl的缺点:

使用此方法不能“取消格式化”或“解析”字符串 你必须搜索所需的格式(例如在维基百科上),不能使用像“yyyy-mm-dd”这样的格式字符串。

这里有一种方法:

var date = Date.parse('Sun May 11,2014');

function format(date) {
  date = new Date(date);

  var day = ('0' + date.getDate()).slice(-2);
  var month = ('0' + (date.getMonth() + 1)).slice(-2);
  var year = date.getFullYear();

  return year + '-' + month + '-' + day;
}

console.log(format(date));

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

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

这很容易由我的date-shortcode包完成:

const dateShortcode = require('date-shortcode')
dateShortcode.parse('{YYYY-MM-DD}', 'Sun May 11,2014')
//=> '2014-05-11'

2020的答案

你可以使用本地的. tolocaledatestring()函数,它支持一些有用的参数,如区域设置(选择MM/DD/YYYY或YYYY/MM/DD格式),时区(转换日期)和格式详细选项(例如:1 vs 01 vs一月)。

例子

const testCases = [ new Date().toLocaleDateString(), // 8/19/2020 new Date().toLocaleString(undefined, {year: 'numeric', month: '2-digit', day: '2-digit', weekday:"long", hour: '2-digit', hour12: false, minute:'2-digit', second:'2-digit'}), new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}), // 08/19/2020 (month and day with two digits) new Date().toLocaleDateString('en-ZA'), // 2020/08/19 (year/month/day) notice the different locale new Date().toLocaleDateString('en-CA'), // 2020-08-19 (year-month-day) notice the different locale new Date().toLocaleString("en-US", {timeZone: "America/New_York"}), // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone) new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"}), // 09 (just the hour) ] for (const testData of testCases) { console.log(testData) }

注意,有时要以特定的格式输出日期,必须找到与该格式兼容的区域设置。 您可以在这里找到本地示例:https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all

请注意locale只是改变格式,如果你想将特定日期转换为特定国家或城市的等效时间,那么你需要使用timezone参数。