【问题标题】:How to remove time portion from Nullable<DateTime> in LINQ如何从 LINQ 中的 Nullable<DateTime> 中删除时间部分
【发布时间】:2016-12-07 08:28:43
【问题描述】:

下面是我的 LINQ

 IQueryable<ReportMapper> query;

                    query = (from c in entities.tDocumentStatus
                             join d in entities.tTOCStructures on c.DocumentId equals d.DocumentID
                             join e in entities.tUsers on d.LastUpdatedBy equals e.UserUID
                             orderby d.CreatedOn descending
                             where
                              (docMode <= 0 || docModes.Contains(c.StatusId)) &&
                              d.FolderType == 2 && d.isDeleted == false && d.ClientID == clientId &&
                              (EntityFunctions.TruncateTime(d.CreatedOn) >= startDate.Date && EntityFunctions.TruncateTime(d.CreatedOn) <= endDate.Date) 
                             select new ReportMapper()
                             {
                                 DocumentName = d.DocumentName,
                                 AssignedDate = c.AssignedDate==null? (EntityFunctions.TruncateTime(d.LastUpdatedOn)):  (EntityFunctions.TruncateTime(c.AssignedDate)),
                                 ReviewStatus = c.tStatu.StatusName,
                                 ActionPerformedBy = e.FirstName + " " + e.LastName
                             });

我需要将此数据导出到 Excel。我需要从分配的日期中删除完整的时间部分。

当我使用EntityFunctions.TruncateTime 时,它会将时间截断为00:00:00

但我需要删除这部分。

我尝试了以下方法:-

  • (EntityFunctions.TruncateTime(d.LastUpdatedOn)).Value.Date
  • (EntityFunctions.TruncateTime(d.LastUpdatedOn).GetValueOrDefault().Date)
  • (EntityFunctions.TruncateTime(d.LastUpdatedOn)).ToString().Date

导出到 Excel

   public void ExportToExcel()
    {
        ExcelPackage excel = new ExcelPackage();
            var worksheet = excel.Workbook.Worksheets.Add("Sheet1");
       fileName = "Document_Status_Report_" + DateTime.Now.ToString("yyyyMMdHHmmss") + ".xlsx";
                worksheet.Cells[1, 1].LoadFromCollection(data, true);
 using (MemoryStream swObj = new MemoryStream())
            {
                response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + "");
                excel.SaveAs(swObj);
                swObj.WriteTo(response.OutputStream);
                return;
            }

    }

【问题讨论】:

  • 属性是DateTime,它总是有一个“时间”组件。如果您只想要日期部分,请将其格式化为字符串
  • 您可以使用DateTime.Date 提取日期时间的日期部分。时间部分可通过DateTime.TimeSpan获得。
  • 如果您在使用 Excel 时遇到问题,请发布 相关 代码。 Excel 的时间部分没有问题 - 它根本没有仅日期的日期!。 Excel 中的日期存储为从 1899-12-30 开始的十进制偏移量。您可以使用DateTime.ToOADate 获得该值。 很多虽然使用像 Epplus 这样的库并让它进行任何转换
  • @PanagiotisKanavos,添加了 ExportToExccel()
  • @Kgn-web 那 Epplus。那有什么问题呢?如果您使用.Date,则单元格将在时间部分包含00:00:00,并且存储的日期值将根本没有秒数(即没有小数部分)。 EntityFunctions.TruncateTime 也是如此。您是否对列使用了仅日期样式?

标签: c# sql-server asp.net-mvc linq datetime


【解决方案1】:

使用.Value.Date,就像您已经尝试过的那样。 从不字符串。

您的问题不在于时间部分(@PanagiotisKanavos 解释说),而是应用于 Excel 中的单元格的 格式。只需调整它以仅显示日期部分。

【讨论】:

  • 我已经添加了我的 ExportToExcel() 你能告诉我在哪里指定日期格式
  • 您可以在工作表中定义一个范围 - 保存日期值的(部分)列 - 然后设置该范围的 Format 属性。
【解决方案2】:

DateTime 总是有时间,你不能从Datetime 截断或删除时间。如果你只想要日期,那么建议在ReportMapper 类中添加新的字符串属性并只分配日期字符串。如下面的代码我已将“MM/dd/yyyy”格式的日期分配给AssignedDateString

IQueryable<ReportMapper> query;

                    query = (from c in entities.tDocumentStatus
                             join d in entities.tTOCStructures on c.DocumentId equals d.DocumentID
                             join e in entities.tUsers on d.LastUpdatedBy equals e.UserUID
                             orderby d.CreatedOn descending
                             where
                              (docMode <= 0 || docModes.Contains(c.StatusId)) &&
                              d.FolderType == 2 && d.isDeleted == false && d.ClientID == clientId &&
                              (EntityFunctions.TruncateTime(d.CreatedOn) >= startDate.Date && EntityFunctions.TruncateTime(d.CreatedOn) <= endDate.Date) 
                             select new ReportMapper()
                             {
                                 DocumentName = d.DocumentName,
                                 AssignedDate = c.AssignedDate==null? (EntityFunctions.TruncateTime(d.LastUpdatedOn)):  (EntityFunctions.TruncateTime(c.AssignedDate)),
                                 ReviewStatus = c.tStatu.StatusName,
                                 ActionPerformedBy = e.FirstName + " " + e.LastName
                                 AssignedDateString= c.AssignedDate==null? (d.LastUpdatedOn.ToString("MM/dd/yyyy")):  (c.AssignedDate.ToString("MM/dd/yyyy")),
                             });

【讨论】:

  • 这种格式会在全球 90% 的地区造成问题。在谈论日期时没有理由使用字符串。如果确实需要使用字符串,请使用明确的格式,例如 ISO8601
  • 哦,这种格式肯定会在 Excel 中失败。 Excel 将日期存储为十进制数。 MM/dd/yyyy 最多将被视为文本,或被解释为错误的日期
  • @PanagiotisKanavos 我同意你的看法。在上面的代码中,不必只使用 'MM/dd/yyyy'。我刚刚建议了如何以特定日期格式格式化 DateTime。
【解决方案3】:

对我来说最好的作品是:-

manufactured_dates = detail.manufactured_date == null ? "" : ((DateTime)detail.manufactured_date).ToShortDateString()

我需要在 LINQ 中从 Nullable&lt;DateTime&gt; 中将日期转换为字符串格式, 所以它是Nullable&lt;DateTime&gt; 我做了

(DateTime)detail.manufactured_date

然后从我应用的转换日期时间值中提取日期作为字符串 Value.ToShortDateString()

即:((DateTime)detail.manufactured_date).ToShortDateString()

或者你也可以这样做

((DateTime)detail.expiry_date).ToString("dd.MMM.yyyy")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    相关资源
    最近更新 更多