2016-07-17 48 views
1

我使用mysqljs並得到結果之後,從sql我得到不同的TimeStamp格式喜歡這一點:的mysql的NodeJS得到正確的時間戳格式

created_at: Sat Jul 16 2016 23:52:54 GMT+0430 (IRDT) 

,但它是在MySQL是:

2016-07-16 23:52:54 

我想得到,而不是其他格式,我如何設置這種格式的MySQL連接或SQL命令?

var connection = mysql.createConnection({ 
    host: 'localhost', 
    user: 'root', 
    password: 'a', 
    database: 'signal' 
}); 

connection.query(command, function (err, rows) { 
    if (err) throw err; 
    console.log(rows); 
}); 

回答

3

我會建議處理行而不是嘗試更改MySQL輸出結果。這樣你的數據庫將有關於created_date的詳細完整數據。而客戶端(其他功能,系統,項目等)會將從數據庫檢索到的值格式化爲他們需要的任何格式。此外,您將通過系統爲日期保持一致的返回結果。無論執行哪種DB查詢,您的軟件始終都會返回相同的格式。

下面是ES6中的一個例子,它還使用了moment.js庫來簡化您將要使用的任何日期操作,強烈建議使用這個庫。

const connection = mysql.createConnection({ 
    host: 'localhost', 
    user: 'root', 
    password: 'a', 
    database: 'signal' 
}); 

function formatDate(date) { 
    return moment(date).format('YYYY-MM-DD HH:mm:ss'); 
} 

connection.query(command, (err, rows) => { 
    if (err) { 
     throw err; 
    } 

    rows = rows.map(row => ({ 
     ...row, 
     created_date: formatDate(row.created_date) 
    })); 

    console.log(rows); 
}); 

更新或ES5

var connection = mysql.createConnection({ 
    host: 'localhost', 
    user: 'root', 
    password: 'a', 
    database: 'signal' 
}); 

function formatDate(date) { 
    return moment(date).format('YYYY-MM-DD HH:mm:ss'); 
} 

connection.query(command, function(err, rows) { 
    if (err) { 
     throw err; 
    } 

    rows = rows.map(function(row) { 
     return Object.assign({}, row, { created_date: formatDate(row.created_date) }); 
    }); 

    console.log(rows); 
}); 
+0

謝謝,但什麼'...行,'?你能完成這個部分嗎? –

+0

我更新了添加ES5樣本 – anvk

+0

謝謝,爲什麼我得到'[]'? 。問題是'無效的參數數量,期望0..1'這部分的代碼'{},行,{create_date:formatDate(row.create_date)}' –

0

這將聽起來難以置信,但它足以稱之爲 '的ToString()' 的時刻字符串。這將給人類可讀的輸出