Javascript 在javascript中将yyyy-MM-dd转换为MM/dd/yyyy

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28246788/
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-23 01:27:16  来源:igfitidea点击:

Convert yyyy-MM-dd to MM/dd/yyyy in javascript

javascript

提问by Abhi

This might be a simple solution but I am stuck, basically I need convert an incoming yyyy-MM-dd to MM/dd/yyyy also, if incoming date is nil, then output should also be nil.

这可能是一个简单的解决方案,但我被卡住了,基本上我还需要将传入的 yyyy-MM-dd 转换为 MM/dd/yyyy,如果传入日期为零,则输出也应该为零。

Incoming date could be of following format

传入日期可以是以下格式

2015-01-25 or nil

Output date shoud be

输出日期应该是

01/25/2015 or nil

I was trying one from the following link Convert Date yyyy/mm/dd to MM dd yyyybut couldn't make it work.

我正在尝试从以下链接 Convert Date yyyy/mm/dd to MM dd yyyy 中的一个,但无法使其工作。

Thanks for any help.

谢谢你的帮助。

Forgot to mention, the incoming date which comes as nil is of the following format in an xml file

忘了说,传入的日期为 nil,在 xml 文件中采用以下格式

<Through_Date__c xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>

So if I get the above format the output should be just be nil

所以如果我得到上面的格式输出应该只是零

回答by hassassin

The date toStringfunction has some support for formatting. See this. And you also want to handle the undefined case which I took from here. So, for your case you can just do this:

日期toString函数有一些格式支持。看到这个。而且您还想处理我从此处获取的未定义案例。因此,对于您的情况,您可以这样做:

function format(inputDate) {
    var date = new Date(inputDate);
    if (!isNaN(date.getTime())) {
        // Months use 0 index.
        return date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear();
    }
}

EDIT: Addressing the comment

编辑:解决评论

If the padding is important you just need to add that in:

如果填充很重要,您只需将其添加到:

var d = date.getDate().toString();
(d[1]?d:"0"+d[0])

I've made an update to the fiddle

我已经更新了小提琴

回答by hassassin

Try using RegEx:

尝试使用正则表达式:

var format = function(input) {
  var pattern = /(\d{4})\-(\d{2})\-(\d{2})/;
  if (!input || !input.match(pattern)) {
    return null;
  }
  return input.replace(pattern, '//');
};

console.log(format('2015-01-25'));
console.log(format('2000-12-01'));
console.log(format(''));
console.log(format(null));

Using String#split and Array#join, push & shift:

使用 String#split 和 Array#join,push & shift:

var format = function(input) {
  var array = (input || '').toString().split(/\-/g);
  array.push(array.shift());
  return array.join('/') || null;
};

console.log(format('2015-01-25'));
console.log(format('2000-12-01'));
console.log(format(''));
console.log(format(null));

回答by hamobi

if you wanna go ghetto style and use easily understandable code, and you dont care about using a date object, try this!

如果你想采用贫民窟风格并使用易于理解的代码,并且你不关心使用日期对象,试试这个!

function changeDateFormat(inputDate){  // expects Y-m-d
    var splitDate = inputDate.split('-');
    if(splitDate.count == 0){
        return null;
    }

    var year = splitDate[0];
    var month = splitDate[1];
    var day = splitDate[2]; 

    return month + '\' + day + '\' + year;
}

var inputDate = '2015-01-25';
var newDate = changeDateFormat(inputDate);

console.log(newDate);  // 01/25/2015

回答by Ben Grimm

If your date has not yet been parsed from a string, you can simply rearrange its components:

如果您的日期尚未从字符串中解析出来,您可以简单地重新排列其组件:

var s = '2015-01-25';
if (s) { 
    s = s.replace(/(\d{4})-(\d{1,2})-(\d{1,2})/, function(match,y,m,d) { 
        return m + '/' + d + '/' + y;  
    });
}

回答by Abhi

Thanks guys, I was able to do grab some ideas from all your posts and came up with this code which seems to working fine in my case

谢谢大家,我能够从你所有的帖子中汲取一些想法,并提出了这段代码,在我的情况下似乎工作正常

if((typeof inStr == 'undefined') || (inStr == null) || 
(inStr.length <= 0)) {
return '';
}
var year = inStr.substring(0, 4);
var month = inStr.substring(5, 7);
var day = inStr.substring(8, 10);
return month + '/' + day + '/' + year;

回答by Hamzeen Hameem

You can also try the method below using vanilla JS. I have converted the date to a string& parsed it to get the format you're looking for:

您也可以使用 vanilla JS 尝试以下方法。我已将日期转换为 a string& 解析它以获得您正在寻找的格式:

function tranformDate(strDate) {
    let result = '';

    if (date) {
      let parts = date.split('-');
      result = `${parts[1]}/${parts[2]}/${parts[0]}`;
    }
    return result;
}

let date = new Date().toISOString().split('T')[0];
console.log('raw date: ' + date);
console.log('formatted date: ' + tranformDate(date));