好的,可以说我有一个每天都会更改的字符串,其中包含日期

var receiveddate = "Received on Saturday 14th of July 2018"


如何将日期提取到示例formatreceiveddate = "2018-07-14"

我知道另一种方法是使用字符串插值和模板文字,而不是如何反转它

所以我真正在问如何改变这个

Received on Saturday 14th of July 2018
Received on Saturday 5th of May 2018
Received on Monday 8th of January 2018
Received on Wednesday 19th of July 2017
Received on Sunday 1st of July 2018
Received on Tuesday 3rd of July 2018
Received on Saturday 2nd of June 2018
Received on Thursday 21st of June 2018
Received on Thursday 31st of May 2018


进入每个日期的2018-07-14

最佳答案

可能有比这更优雅的方法,但这是我想到的第一件事。拆分字符串,并使用它创建一个日期对象。



const dateString = "Received on Saturday 14th of July 2018";

// Split the string up by spaces
const dateParts = dateString.split(' ');

// Grab each part of the date. We parse the day as an int to just get the numeral value
const month = dateParts[5];
const day = parseInt(dateParts[3]);
const year = dateParts[6];

// Parse the date by reassembling the string
const date = new Date(month + ' ' + day + ' ' + year);

// Output in your desired format (ISO)
const formattedDate = date.getFullYear()+'-' + (date.getMonth()+1) + '-'+date.getDate();

console.log(formattedDate);

10-07 17:41