2016-05-12 92 views
-1

我有日期這樣的:爲什麼我用下面的formatDate函數得到相同的日期?

2016-05-12T09:49:01.547Z 
2016-05-09T11:18:57.006Z 
2016-05-12T09:49:01.547Z 

我使用這個功能:

function formatDate (date) { 
    const dateObj = new Date() 
    const y = dateObj.getFullYear() 
    const m = dateObj.getMonth(date) + 1 
    const d = dateObj.getDate(date) 
    return y + '/' + m + '/' + d 
} 

這樣:

功能buildingTemplate(建築){ 日期:formatDate(建築。 updatedAt) isDirty:false } }

要產生這樣的:

2016/5/12 
2016/5/12 
2016/5/12 

但你可以看到今天的日期始終,而不是我想轉換爲格式的日期。

這是爲什麼?

+0

你沒有使用'date'參數。 –

+0

您需要刪除'const dateObj = new Date()',而是使用傳遞給函數的參數 –

回答

1

變化的功能波紋管

function formatDate(date) { 
 
    const dateObj = new Date(date); 
 
    const y = dateObj.getFullYear(); 
 
    const m = dateObj.getMonth() + 1; 
 
    const d = dateObj.getDate(); 
 
    return y + '/' + m + '/' + d; 
 
}

1

您完全忽略了通過的date參數。把它放入Date對象構造:

const dateObj = new Date(date); 

如果不帶任何參數來創建new Date(date)對象,你會得到當前的日期 - 這就是爲什麼你有特里普爾2016/5/12

1

您錯誤地使用了date。你應該函數看起來像:

function formatDate (date) { 
    const dateObj = new Date(date) 
    const y = dateObj.getFullYear() 
    const m = dateObj.getMonth() + 1 
    const d = dateObj.getDate() 
    return y + '/' + m + '/' + d 
} 

而且,我想建議你http://momentjs.com/庫,這是帶有日期的工作標準librabry。它有很大的API和小尺寸。

相關問題