简体   繁体   English

如何将日期格式从YYYY-DD-MM转换为DD-MM-YYYY

[英]How to convert date format from YYYY-DD-MM to DD-MM-YYYY

I have a date as 2014-12-03 我的约会日期是2014-12-03

I need to convert this to DD-MM-YYYY 我需要将其转换为DD-MM-YYYY

I have tried as 我尝试过

var from = "2014-12-03"; 
var numbers = from.match(/\d+/g); 
var date = new Date(numbers[2], numbers[0]-1, numbers[1]);
alert(date);

This is my jsfiddle 这是我的jsfiddle

http://jsfiddle.net/bnz9d6gz/ http://jsfiddle.net/bnz9d6gz/

Could anybody please help me . 有人可以帮我吗。

Cut your date string into 3 pieces, reverse order, and glue it back 将您的日期字符串切成3块,反向排列,然后重新粘贴

"2014-12-03".split('-').reverse().join('-'); // "03-12-2014"

Breakdown: 分解:

  1. "2014-12-03" - string "2014-12-03" -字符串
  2. ['2014','12','03'] - create an array by splitting each string which isn't - ['2014','12','03'] -通过拆分不是的每个字符串来创建数组-
  3. ['03','12','2014'] - reversing the array ['03','12','2014'] -反转数组
  4. "03-12-2014" - joining all items in the array and putting - between them. "03-12-2014" -在阵列中加入的所有项目,并把-他们之间。

How about this: 这个怎么样:

var from = "2014-12-03"; 

function convert(date){
    var d=new Date(date);
    function addLeadingZero(d){
        return (d<10)?"0"+d:d;
    }
    return [d.getDay(), d.getMonth()+1, d.getFullYear()].map(addLeadingZero).join("-");
}

console.log(convert(from));

Fiddle updated. 小提琴更新。

If I were you I'd use momentJS , it'll handle this kind of thing for you. 如果我是您,我将使用momentJS ,它将为您处理这种事情。 If you pull in the library all you'll need to do is: 如果拉入库,您所需要做的就是:

var from = moment("2014-12-03", "YYYY-MM-DD");
var date = moment.format("DD/MM/YYYY");
alert(date);

Much easier than trying to roll your own solution and if you ever need to support additional formats it'll make your life easy. 这比尝试推出自己的解决方案要容易得多,而且如果您需要支持其他格式,那将使您的生活变得轻松。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM