Convert Date from one format to another format in JavaScript

后端 未结 4 1509
说谎
说谎 2020-12-03 18:40

I have a string of a date in javascript in format #1. I need to convert it to format #2.

The problem starts when one format is \"dd/mm/yy\" and the other is \"mm/dd/

4条回答
  •  感动是毒
    2020-12-03 18:55

    You can use the function below

    console.log(changeDateFormat('12/1/2020','dd/MM/yyyy','MM/dd/yyyy'));
    
    function changeDateFormat(value, inputFormat, outputFormat) {
    
    let outputSplitter = "/";
    let strOutputFormat = outputFormat.split(outputSplitter).map(i => i.toUpperCase());
    if (strOutputFormat.length != 3) {
      strOutputFormat = outputFormat.split('-');
      outputSplitter = '-';
    }
    
    if (strOutputFormat.length != 3) throw new Error('wrong output format splitter :(');
    
    let date = null;
    
    if (value instanceof Date) {
      date = {
        ["YYYY"]: value.getUTCFullYear(),
        ["MM"]: value.getMonth() + 1,
        ["DD"]: value.getDate()
      }
    }
    
    if (typeof value == 'string') {
      let inputSplitter = "/";
    
      var strInputFormat = inputFormat.split(inputSplitter).map(i => i.toUpperCase());
      if (strInputFormat.length != 3) {
        strInputFormat = inputFormat.split('-');
        inputSplitter = '-';
      }
    
      if (strInputFormat.length != 3) throw new Error('wrong input format splitter :(');
    
      let dateElements = value.split(inputSplitter);
      if (dateElements.length != 3) throw new Error('wrong value :(');
    
      date = {
        [strInputFormat[0]]: dateElements[0],
        [strInputFormat[1]]: dateElements[1],
        [strInputFormat[2]]: dateElements[2],
      }
    }
    
    if (!date) throw new Error('unsupported value type:(');
    
    let result = date[strOutputFormat[0]] + outputSplitter
      + date[strOutputFormat[1]] + outputSplitter 
      + date[strOutputFormat[2]];
    
    return result;
     }
    

提交回复
热议问题