JQGrid 4.4.0: средство форматирования «даты» srcformat/newformat теперь пытается отформатировать дату, если исходный формат даты не соответствует srcformat.

У меня есть JQGrid со столбцом даты. Я использую средство форматирования даты для форматирования даты в формате m/d/Y. Раньше, если формат исходной даты не соответствовал srcformat, который я передал в formatoptions, дата просто не форматировалась. JQGrid v4.4.0 теперь пытается отформатировать дату независимо от исходного формата и выдает даты, которые сильно отличаются :-).

Даты, которые я заполняю в этом столбце, могут быть либо уже в правильном формате (m/d/Y), либо в формате, который я определил в srcformat (Y-m-dTH:i:s).

Есть ли способ в JQGrid 4.4.0 не пытаться анализировать даты, которые не соответствуют srcformat?


Мое определение colModel для столбца:

{name:"date", index:"date", label:"Date", width:85, jsonmap:"date", hidden: false, formatter:'date', sorttype: 'date', formatoptions:{srcformat:'Y-m-dTH:i:s', newformat:'m/d/Y'}, searchrules: { date: true } }        

person icats    schedule 09.07.2012    source источник


Ответы (2)


Я решил свою проблему :)

Я создал собственный модуль форматирования и использовал библиотеку JQuery Datejs для анализа даты.

В основном средство форматирования форматирует дату только в формате m/d/Y, если она находится в формате Y-m-dTH:i:s; в противном случае он предполагает, что он уже находится в формате m/d/Y, и оставляет его таким.

/**
 * This function formats the date column for the summary grid.
 * 
 * The grid could be populated with dates that are in m/d/Y format or in Y-m-dTH:i:s format; need
 * to account for this; want the dates to end up being in m/d/Y format always.
 * 
 * @param cellvalue     is the value to be formatted
 * @param options       an object containing the following element
 *                      options : { rowId: rid, colModel: cm} where rowId - is the id of the row colModel is the object of the properties for this column getted from colModel array of jqGrid
 * @param rowObject     is a row data represented in the format determined from datatype option;
 *                      the rowObject is array, provided according to the rules from jsonReader
 * @return              the new formatted cell value html
 */
function summaryGridDateFormatter(cellvalue, options, rowObject) {

    // parseExact just returns 'null' if the date you are trying to 
    // format is not in the exact format specified
    var parsedDate = Date.parseExact(cellvalue, "yyyy-MM-ddTHH:mm:ss"); 

    // if parsed date is null, just used the passed cell value; otherwise, 
    // transform the date to desired format
    var formattedDate = parsedDate ? parsedDate.toString("MM/dd/yyyy") : cellvalue;

    return formattedDate;
}
person icats    schedule 10.07.2012

@icats: спасибо за это! это действительно помогло - я начал сильно расстраиваться...

Мне действительно пришлось немного изменить вашу функцию. Я получал поле timestamp из БД, которое возвращалось через JSON в виде значения в миллисекундах (т. е. фактическое значение было примерно таким: 1343314489564). Поэтому я добавил вторую проверку для parsedDate, как показано ниже:

/**
 * This function formats the date column for the  grid.
 *
 * The grid could be populated with dates that are in m/d/Y format or in Y-m-dTH:i:s format; need
 * to account for this; want the dates to end up being in m/d/Y format always.
 *
 * @param cellvalue     is the value to be formatted
 * @param options       an object containing the following element
 *                      options : { rowId: rid, colModel: cm} where rowId - is the id of the row colModel is the object of the properties for this column getted from colModel array of jqGrid
 * @param rowObject     is a row data represented in the format determined from datatype option;
 *                      the rowObject is array, provided according to the rules from jsonReader
 * @return              the new formatted cell value html
 */
function dateFormatter(cellvalue, options, rowObject) {

    // parseExact just returns 'null' if the date you are trying to
    // format is not in the exact format specified
    var parsedDate = Date.parseExact(cellvalue, "yyyy-MM-ddTHH:mm:ss");
    if(parsedDate == null )
        parsedDate = new Date(cellvalue);

    // if parsed date is null, just used the passed cell value; otherwise,
    // transform the date to desired format
    var formattedDate = parsedDate ? parsedDate.toString("yyyy-MM-dd HH:mm:ss") : cellvalue;

    return formattedDate;
}
person gsaslis    schedule 31.07.2012