如何使用 javascript/jquery 反转日期格式 yyyy-mm-dd?

新手上路,请多包涵

我想将格式为 2016-10-15 的数据的日期更改为 d-m-yy jquery 中的格式为 15-10-2016 控制它显示的输出 - 我试过了 2016-10-15 。我在从数据库中获取的 jquery ajax 页面中捕获了这个结果。

 $.each(req,function(i,item){
    var val=$.format.date(req[i].from_date, "dd/MMM/yyyy");
    console.log(val);   //'2016-10-15'
});

原文由 user3386779 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 287
2 个回答

您可以使用本机 javascript 函数来完成这项工作。 Use .split() to split date by - delimiter into array and invert array using .reverse() and convert array to sting using .join()

 var date = "2016-10-15";
date = date.split("-").reverse().join("-");
console.log(date);

原文由 Mohammad 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用正则表达式很容易 .replace()

 var input = "2016-10-15";
var output = input.replace(/(\d{4})-(\d\d)-(\d\d)/, "$3-$2-$1");
console.log(output);

您可以轻松地让正则表达式接受多个分隔符:

 var re = /(\d{4})[-. \/](\d\d)[-. \/](\d\d)/;

console.log("2015-10-15".replace(re, "$3-$2-$1"));
console.log("2015.10.15".replace(re, "$3-$2-$1"));
console.log("2015 10 15".replace(re, "$3-$2-$1"));
console.log("2015/10/15".replace(re, "$3-$2-$1"));

原文由 nnnnnn 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题