在 JavaScript 中将日期从一种格式转换为另一种格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26500694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:58:31  来源:igfitidea点击:

Convert Date from one format to another format in JavaScript

javascriptdatedate-format

提问by TamarG

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

我在javascript中有一个日期字符串,格式为#1。我需要将其转换为格式 #2。

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

当一种格式是“dd/mm/yy”而另一种格式是“mm/dd/yy”时,问题就开始了。

The formats change dynamically and I have the formats as strings, but I need a function like

格式动态变化,我将格式作为字符串,但我需要一个像

   Date newDate = convert(currentDate, currentFormatString, newFormatString).

How can I do it?

我该怎么做?

回答by trekforever

You should look into momentjs, which is a javascript date/time library. With that, you can easily convert between dates of different format. In your case, it would be:

您应该查看momentjs,它是一个 javascript 日期/时间库。有了它,您可以轻松地在不同格式的日期之间进行转换。在您的情况下,它将是:

string newDate = moment(currentDate, currentFormatString).format(newFormatString)

string newDate = moment(currentDate, currentFormatString).format(newFormatString)

For example, moment("21/10/14", "DD/MM/YY").format("MM/DD/YY")would return "10/21/14"

例如,moment("21/10/14", "DD/MM/YY").format("MM/DD/YY")会返回"10/21/14"

回答by M. Ali

You can use the above described answer of momnet.js or the function below for splitting and using it

您可以使用 momnet.js 的上述答案或以下功能进行拆分和使用

For using moment.js make sure you enter your old and new format in upper case

对于使用 moment.js,请确保以大写形式输入旧格式和新格式

function parseDate(strDate) {

    var dateFormat = $('#currentDateFormat').val();

    var str;
    var res;

    var strFormat = dateFormat.split('.');
    if (strFormat.length != 3)
        strFormat = dateFormat.split('/');
    if (strFormat.length != 3)
        strFormat = dateFormat.split('-');

    str = strDate.split('.');
    if (str.length != 3)
        str = strDate.split('/');
    if (str.length != 3)
        str = strDate.split('-');


    if (strFormat[0].substr(0, 1) == 'd' && strFormat[1].substr(0, 1) == 'M' &&             
        strFormat[2].substr(0, 1) == 'y') // for dd MM yyyy
        res = new Date(str[2], str[1], str[0]);

    if (strFormat[0].substr(0, 1) == 'M' && strFormat[1].substr(0, 1) == 'd' &&
        strFormat[2].substr(0, 1) == 'y') // for MM dd yyyy
        res = new Date(str[2], str[0], str[1]);

    if (strFormat[0].substr(0, 1) == 'y' && strFormat[1].substr(0, 1) == 'M' &&
        strFormat[2].substr(0, 1) == 'd')
        res = new Date(str[0], str[1], str[2]);

    if (strFormat[0].substr(0, 1) == 'y' && strFormat[1].substr(0, 1) == 'd' &&         
        strFormat[2].substr(0, 1) == 'M')
        res = new Date(str[0], str[2], str[1]);

    return res;
}

回答by Feng Lin

It seems that you should use the library of query-dateformat git hub for jquery-dateformat
or you can use the normal function like date-time-formate, use the library to config the formate template

看来你应该使用 query-dateformat git hub的库来处理 jquery-dateformat
或者你可以使用像date-time-formate这样的普通函数,使用该库来配置 formate 模板

回答by Osama AbuSitta

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;
 }