2016-07-22 195 views
1

日期:10/02/2014(DD/MM/YYYY)。 如何將其轉換爲時間戳格式。將時間戳轉換爲日期並將日期轉換爲時間戳記格式

以及如何更改date.When的我寫這樣的代碼格式:對於當前日期

var current_date=new Date(); -->i got result like MM/DD/YYYY format. 

我想DD/MM/YYYY格式。

+0

10/02/2014 **是** [*時間戳*](https://en.wikipedia.org/wiki/Timestamp)。 ;-) – RobG

回答

0

使用dateFormat庫。

var current_date = new Date(); 
dateFormat(current_date, "dd/mm/yyyy"); 

以「dd/mm/yyyy」格式返回日期。

+0

謝謝你的回覆bro.Its運作良好。@ sainath batthala – Trojan

0

你在這裏

var current_date=new Date(); 
var timestamp = current_date.getTime(); 
var formatted_date = current_date.getDate() + "/" + current_date.getMonth() + 1 + "/" + current_date.getFullYear() 
+0

感謝@Ruben karapetyan.Its非常容易理解。再次感謝您的回覆。其工作正在進行中 – Trojan

+0

歡迎您! –

0

「timestamp」我想你的意思是時間值,如1391954400000

要將日期字符串轉換爲日期,您需要解析它。使用庫或簡短功能。然後,你可以得到的時間價值,這表示從1970-01-01T00毫秒數:00:00Z:

/* Parse date sting in d/m/y format 
 
** @param {string} s - date string in d/m/y format 
 
**      separator can be any non–digit character 
 
** @returns {Date} If s is an invalid date, returned 
 
**     Date has time value of NaN (invalid date) 
 
*/ 
 
function parseDMY(s) { 
 
    var b = s.split(/\D/); 
 
    var d = new Date(b[2], --b[1], b[0]); 
 
    return d && d.getMonth() == b[1]? d : new Date(NaN); 
 
} 
 

 
// Valid date 
 
console.log(parseDMY('10/02/2014').getTime()); 
 

 
// Invalid date 
 
console.log(parseDMY('14/20/2016').getTime());

也有很多圖書館的格式化日期(例如,Fecha.js並解析和格式化),或再次,如果你只有一個格式,一個簡單的函數就可以了:

/* Return date string in format dd/mm/yyy 
 
** @param {Date} d - date to format, default to today 
 
** @returns {string} date in dd/mm/yyyy format 
 
*/ 
 
function formatDMY(d) { 
 
    // Default to today 
 
    d = d || new Date(); 
 
    return ('0' + d.getDate()).slice(-2) + '/' + 
 
     ('0' + (d.getMonth() + 1)).slice(-2) + '/' + 
 
     ('000' + d.getFullYear()).slice(-4); 
 
} 
 

 
console.log(formatDMY()); 
 
console.log(formatDMY(new Date(2016,1,29)));