Как извлечь месяц из даты и времени? - PullRequest
0 голосов
/ 27 ноября 2018

У меня есть модель с недействительным полем созданной даты.Я хочу извлечь месяц из этой даты.Вот мой код в методе контроллера.Я думаю, что проблема в запросе LINQ.Можете ли вы помочь мне исправить этот запрос?Теперь значение reslts для этого запроса равно нулю.

 public JsonResult GetDispatchNoteByMonth(string month)
        {
            IEnumerable<Domain.DispatchNote.DispatchNote> dispatchNotes = _dispatchNoteService.GetAllDispatchNote().Where(d => d.Status == "Open" && d.CreatedDate.GetValueOrDefault().Month.ToString().Contains(month));
            IEnumerable<DispatchNoteViewModel> models = Mapper.Map<IEnumerable<DispatchNoteViewModel>>(dispatchNotes);

            if(models.Count() > 0)
            {
                return Json(new { IsDataAvailable = true, DispatchNotes = models }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { IsDataAvailable = false, Message = "No Dispatch notes found" }, JsonRequestBehavior.AllowGet);
            }
        }

Я передаю значение месяца, выбирая раскрывающееся значение.Вот мой код JavaScript,

$ ("# monthDropdown"). Change (function () {$ ('. Tbtr'). NextAll ('tr'). Remove (); $ ('# openDispatchNoteTable.tbtr '). after (' '); //$('#spinnerContainer').jmspinner();

var selectedValue = $("#monthDropdown").val();

if(selectedValue != ""){
    $.ajax({
        url: "/Dispatch/GetDispatchNoteByMonth?month=" + selectedValue,
        cache: false,
        type: "GET",
        success: function (response) {
            $('#openDispatchNoteTable').find("tr:not(:first)").remove();
            $('#spinnerContainer').jmspinner(false);
            if (response.IsDataAvailable) {
                $('.tbtr').nextAll('tr').remove();
                for (var i = 0 ; i <= response.DispatchNotes.length ; i++){
                    if (response.DispatchNotes[i].CreatedDate != null) {
                        $('.tbtr').nextAll('tr').remove();
                        $('#openDispatchNoteTable .tbtr').after('<tr><td> <input type="checkbox" class="dispatchNotesToInvoiceCb" name="dispatchNotesToInvoice" value="' + response.DispatchNotes[i].DispatchNoteId + '" /></td><td>' + response.DispatchNotes[i].DispatchId + '</td><td>' + response.DispatchNotes[i].Client + '</td><td>' + response.DispatchNotes[i].CompanyAddress + '</td><td>' + response.DispatchNotes[i].Quantity + '</td><td>' + response.DispatchNotes[i].Driver + '</td><td>' + response.DispatchNotes[i].VehicleLicensePlateNumber + '</td><td>' + moment(new Date(parseInt(response.DispatchNotes[i].DispatchDate.substr(6))).toLocaleDateString()).format('YYYY-MMMM-DD') + '</td><td>' + response.DispatchNotes[i].CreatedUser + '</td><td>' + moment(new Date(parseInt(response.DispatchNotes[i].CreatedDate.substr(6))).toLocaleDateString()).format('YYYY-MMMM-DD') + '</td><td><a class="editbtn btn btn-default btn-raised" href="/Dispatch/ClosedCancelledView/' + response.DispatchNotes[i].DispatchNoteId + '">View<div class="ripple-container"></div></a></td></tr>');
                    } else {
                        $('.tbtr').nextAll('tr').remove();
                        $('#openDispatchNoteTable .tbtr').after('<tr><td> <input type="checkbox" class="dispatchNotesToInvoiceCb" name="dispatchNotesToInvoice" value="' + response.DispatchNotes[i].DispatchNoteId + '" /></td><td>' + response.DispatchNotes[i].DispatchId + '</td><td>' + response.DispatchNotes[i].Client + '</td><td>' + response.DispatchNotes[i].CompanyAddress + '</td><td>' + response.DispatchNotes[i].Quantity + '</td><td>' + response.DispatchNotes[i].Driver + '</td><td>' + response.DispatchNotes[i].VehicleLicensePlateNumber + '</td><td>' + moment(new Date(parseInt(response.DispatchNotes[i].DispatchDate.substr(6))).toLocaleDateString()).format('YYYY-MMMM-DD') + '</td><td>' + response.DispatchNotes[i].CreatedUser + '</td><td></td><td><a class="editbtn btn btn-default btn-raised" href="/Dispatch/ClosedCancelledView/' + response.DispatchNotes[i].DispatchNoteId + '">View<div class="ripple-container"></div></a></td></tr>');
                    }
                }
            } else {
                $('#checkAll').prop('disabled', true);
                $('.tbtr').nextAll('tr').remove();
                $('#openDispatchNoteTable .tbtr').after('<tr><td colspan="11" align="center" style="color:red">' + response.Message + ' ' + $("#monthDropdown option:selected").text() + '</td></tr>');
            }
        },
        error: function (reponse) {
            console.log(reponse);
            $('.tbtr').nextAll('tr').remove();
            $('#spinnerContainer').jmspinner(false);
            $('#openDispatchNoteTable .tbtr').after('<tr><td colspan="11" align="center" style="color:red">Error occured while fetching dispatch notes. Please try again.</td></tr>');
        }
    })
}
else {
    $('.tbtr').nextAll('tr').remove();
    $('#spinnerContainer').jmspinner(false);
}

})

1 Ответ

0 голосов
/ 27 ноября 2018

Метод DateTime.Month возвращает целое число, которое основано на 1: январь равен 1, а декабрь равен 12.

В вашем случае вы должны проверить, какой формат месяцапеременная держит.Если ваш формат месяца - «MMM» (то есть «jan»), тогда вам нужно преобразовать поле CreatedDate date

d.CreatedDate.GetValueOrDefault().Month.ToString("MMMM") 




IEnumerable<Domain.DispatchNote.DispatchNote> dispatchNotes = _dispatchNoteService.GetAllDispatchNote().Where(d => d.Status == "Open" && d.CreatedDate.GetValueOrDefault().Month.ToString("MMMM").ToLower().Contains(month).ToLower());
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...