JS string format conversion problem, unformatted date converted to formatted?

I hope to change the date format of 20181130 to the format of 2018-11-30. Is there any fast conversion plan?


if it is a string of fixed length, you can use regular conversion

let str = '20181130';

let result = str.replace(/(\d{4})(\d{2})(\d{2})/g, '$1-$2-$3');

traverse it. There is no native method


this date conversion is a bit troublesome. I hope it will be helpful to give you a reference:
search c.dates after entering
check this line of code:

/**
 * {@link Date}
 * @param dateStr 
 * @param pattern : yMdHmsS
 * @returns {Date|null} , null
 */
parser: function (dateStr, pattern)

overall idea:

  1. first determine what the rule of the date string pattern is, and then parse it one by one and set it to the date object Date
  2. .
  3. when formatting a date object instance format () for the specified rule pattern

this actually depends on whether your original data is regular or not. if it is regular enough, for example, it is clearly 8-digit characters, then the answer now is a faster method.

otherwise it is actually a very complicated problem.

even the method used has many limitations, such as not being able to prompt for invalid dates.

Menu