locked
Set Date Format in Lamda Expression RRS feed

  • Question

  • User2012297617 posted

    I got this line of code that gets me a date in this format: 10/18/2018 12:00:00 AM

    @OrderHeader.OrderDetails.Select(x => x.TheOrderDate).FirstOrDefault()

    How do I change it to get the date in this format? 10-18-2018

    Friday, August 16, 2019 3:29 PM

Answers

  • User283571144 posted

    Hi lesponce,

    If the type of “TheOrderDate” is “DateTime”:

    public DateTime TheOrderDate { get; set; }

    You could try this command:

    @OrderHeader.OrderDetails.Select(x => x.TheOrderDate).FirstOrDefault().ToString("MM-dd-yyyy")

    In case that the type of “TheOrderDate” is “DateTime?”, you should add ”?” after FirstOrDefault() like this:

    public DateTime? TheOrderDate { get; set; }
    @(OrderHeader.OrderDetails.Select(x => x.TheOrderDate).FirstOrDefault()?.ToString("MM-dd-yyyy"))

    The result:

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 19, 2019 7:27 AM

All replies

  • User303363814 posted

    @OrderHeader.OrderDetails.Select(x => x.TheOrderDate).FirstOrDefault().ToString("MM-dd-yyyy")

    (you will get 01-01-0001 if there is no value)

    Monday, August 19, 2019 5:02 AM
  • User283571144 posted

    Hi lesponce,

    If the type of “TheOrderDate” is “DateTime”:

    public DateTime TheOrderDate { get; set; }

    You could try this command:

    @OrderHeader.OrderDetails.Select(x => x.TheOrderDate).FirstOrDefault().ToString("MM-dd-yyyy")

    In case that the type of “TheOrderDate” is “DateTime?”, you should add ”?” after FirstOrDefault() like this:

    public DateTime? TheOrderDate { get; set; }
    @(OrderHeader.OrderDetails.Select(x => x.TheOrderDate).FirstOrDefault()?.ToString("MM-dd-yyyy"))

    The result:

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 19, 2019 7:27 AM
  • User-1038772411 posted

    Hi lesponce, 

    Try This One For 24Hr.

    @(OrderHeader.OrderDetails.Select(x => x.TheOrderDate).FirstOrDefault()?.ToString("dd/MM/yyyy HH:mm:ss"))

    or 12Hr

    @(OrderHeader.OrderDetails.Select(x => x.TheOrderDate).FirstOrDefault()?.ToString("dd/MM/yyyy hh:mm:ss tt"))

    Monday, August 19, 2019 7:36 AM
  • User-1151440187 posted

    @OrderHeader.OrderDetails.Select(x => x.TheOrderDate).FirstOrDefault().ToString("MM/DD/YYYY")

    Thursday, August 29, 2019 4:33 AM