1. 程式人生 > >關於資料庫欄位為DATE型別的日期處理

關於資料庫欄位為DATE型別的日期處理

資料庫查詢出來欄位為TIMESTAMP型別
一般建議不使用
MySql的  DATE_FORMAT(T.EVENT_DATE, '%Y-%m-%d %H:%i:%S')
或者
 Oracle的 to_char(date,’format’) 
在sql語句做轉換String

如果換資料庫得修改程式碼,所以最好是在js做轉換

/**
 * 將日期格式化成指定格式的字串
 * @param date 要格式化的日期,不傳時預設當前時間,也可以是一個時間戳
 * @param fmt 目標字串格式,支援的字元有:y,M,d,q,w,H,h,m,S,預設:yyyy-MM-dd HH:mm:ss
 * @returns 返回格式化後的日期字串
 */
function formatDate(date, fmt)
{
    date = date == undefined ? new Date() : date;
    date = typeof date == 'number' ? new Date(date) : date;
    fmt = fmt || 'yyyy-MM-dd HH:mm:ss';
    var obj =
    {
        'y': date.getFullYear(), // 年份,注意必須用getFullYear
        'M': date.getMonth() + 1, // 月份,注意是從0-11
        'd': date.getDate(), // 日期
        'q': Math.floor((date.getMonth() + 3) / 3), // 季度
        'w': date.getDay(), // 星期,注意是0-6
        'H': date.getHours(), // 24小時制
        'h': date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, // 12小時制
        'm': date.getMinutes(), // 分鐘
        's': date.getSeconds(), // 秒
        'S': date.getMilliseconds() // 毫秒
    };
    var week = ['天', '一', '二', '三', '四', '五', '六'];
    for(var i in obj)
    {
        fmt = fmt.replace(new RegExp(i+'+', 'g'), function(m)
        {
            var val = obj[i] + '';
            if(i == 'w') return (m.length > 2 ? '星期' : '周') + week[val];
            for(var j = 0, len = val.length; j < m.length - len; j++) val = '0' + val;
            return m.length == 1 ? val : val.substring(val.length - m.length);
        });
    }
    return fmt;
}


//使用示例
$(function(){
formatDate(); // 2016-09-02 13:17:13
formatDate(new Date(), 'yyyy-MM-dd'); // 2016-09-02
// 2016-09-02 第3季度 星期五 13:19:15:792
formatDate(new Date(), 'yyyy-MM-dd 第q季度 www HH:mm:ss:SSS');
formatDate(1472793615764); // 2016-09-02 13:20:15
});