将UTC日期转换为dd / mm / yyyy格式

时间:2014-03-27 12:53:18

标签: javascript date

尝试在JavaScript中将UTC日期格式转换为dd / mm / yyyy时遇到一些困难:

var launchDate = attributes["launch_date"];
if (isBuffering) {
         var date = new Date(launchDate);
         var d = new Date(date.toLocaleDateString());
         launchDate = ((d.getUTCMonth() + 1) + "/" + (d.getUTCDate() + 1) + "/" + (d.getUTCFullYear()));
 } 

我试过这个,但它给我一个无效的日期。所以我改为:

var launchDate = attributes["launch_date"];
if (isBuffering) {
         var date = new Date(launchDate);
         var d = formatDate(new Date(date.toLocaleDateString()));
         launchDate = ((d.getUTCMonth() + 1) + "/" + (d.getUTCDate() + 1) + "/" + (d.getUTCFullYear()));
 }

但是,它仍然返回无效日期。我想知道有没有办法改变格林威治标准时间2013年5月31日17:41:01 GMT + 0200(CEST)到dd / mm / yyyy的日期格式?

提前致谢。

4 个答案:

答案 0 :(得分:7)

var d = new Date();
var n = d.toLocaleDateString();

这在构建JS方法中会更优越!

答案 1 :(得分:5)

function formatDate(d)
 {
  date = new Date(d)
  var dd = date.getDate(); 
  var mm = date.getMonth()+1;
  var yyyy = date.getFullYear(); 
  if(dd<10){dd='0'+dd} 
  if(mm<10){mm='0'+mm};
  return d = dd+'/'+mm+'/'+yyyy
}

答案 2 :(得分:0)

月份为0索引,但日期不是。您无需在当天添加1个。

另外,你要格式化为MM / dd / yyyy,而不是dd / MM / yyyy。

溶液:

var launchDate = attributes["launch_date"];
if (isBuffering) {
         var date = new Date(launchDate);
         var d = formatDate(new Date(date.toLocaleDateString()));
         launchDate = ((d.getUTCDate())+ "/" + (d.getUTCMonth() + 1)  "/" + (d.getUTCFullYear()));
 }

答案 3 :(得分:0)

试一试:

Date.parseExact(Your_Date, 'dd/MM/yyyy').toString('MM/dd/yyyy');

Date.parseExact(Your_Date, 'MM/dd/yyyy').toString('dd/MM/yyyy');