用错误的转换将长日期转换为短日期

时间:2018-12-06 05:53:11

标签: javascript

这是我的长途旅行:

Fri Dec 07 2018 05:47:22 GMT+0000

但是当我将其转换为短日期时,它返回了错误的日期:

var date = 'Fri Dec 07 2018 05:47:22 GMT+0000';
var convertedStartDate = new Date(date);
var year    = convertedStartDate.getFullYear();
var month   = convertedStartDate.getMonth();
var day     = convertedStartDate.getDay();
console.log(year+'/'+month+'/'+day)

浏览器的输出:

2018/11/5

enter image description here

我的Mac OS日期: enter image description here

2 个答案:

答案 0 :(得分:2)

var date = 'Fri Dec 07 2018 05:47:22 GMT+0000';
var convertedStartDate = new Date(date);
var year          = convertedStartDate.getFullYear();    // 2018
var month_index   = convertedStartDate.getMonth();       // 11  month name index
var weekday_index = convertedStartDate.getDay();         // 5   weekday index
var day_date      = convertedStartDate.getDate();        // 7

var day_names = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];

var month_names = ["Jan","Feb","Mar","Apr",
                   "May","Jun","Jul","Aug",
                   "Sep","Oct","Nov","Dec"];
                   
var month_name = month_names[month_index];               // Dec
var day = day_names[weekday_index];                      // Fri


console.log(day+" "+day_date+"-"+month_name+"-"+year);   // Fri 7-Dec-2018

console.log(year+"/"+(month_index+1)+"/"+day_date);      // 2018/12/7

var month = convertedStartDate.getMonth(); 

这将返回0到11之间的值... 原因是您可能在类似以下的数组中使用此索引:

  var month_names = ["jan","feb", .... "dec"];
  console.log(month_names[month]);   //dec

但是,如果您只对数值感兴趣,只需加1

  var month = convertedStartDate.getMonth() + 1; 

对于getDay(),它将返回0到6之间的值,以便您可以像这样使用它:

 var day     = convertedStartDate.getDay();
 var day_names = ['Sun', 'Mon',... ,'Sat'];
 console.log(day_names[day]);    

,但是如果您只需要数字值(介于1和28/29/30/31之间),则需要.getDate()而不是.getDay()。但是,在这种情况下,无需添加一个。

答案 1 :(得分:0)

var date = 'Fri Dec 07 2018 05:47:22 GMT+0000';
var convertedStartDate = new Date(date);
var year    = convertedStartDate.getFullYear();
var month   = convertedStartDate.getMonth() + 1;
var day     = convertedStartDate.getDate();
console.log(year+'/'+month+'/'+day)

getDay()方法替换为getDate()并在月份中加上1,因为getMonth()将在0-11之间返回

看,我添加了工作示例,也希望它能解决问题。