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


当前回答

不需要库

纯JavaScript。

下面的例子是从今天开始的两个月:

var d = new Date() d.setMonth(d.getMonth() - 2); var dateString =新的日期(d); console.log('格式化前',dateString, '格式化后',dateString. toisostring ().slice(0,10))

其他回答

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

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参数。

你可以:

函数formatDate(日期){ var d = new Date(日期), 月= " + (d.getMonth() + 1) ", day = " + d.getDate(), year = d.g getfullyear (); 如果(月。长度< 2) 月= '0' +月; 如果一天。长度< 2) Day = '0' + Day; 返回[年,月,日].join('-'); } console.log(formatDate('Sun May 11,2014'));

使用的例子:

console.log(formatDate('Sun May 11,2014'));

输出:

2014-05-11

JSFiddle的演示:http://jsfiddle.net/abdulrauf6182012/2Frm3/

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

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

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