Formatting date in View

Joe Green 146 Reputation points
2022-12-19T18:41:47.763+00:00

In my asp.net MVC C# app, I have defined this

        [DisplayFormat(DataFormatString = "{0:yymmdd}", ApplyFormatInEditMode = true)]  
        public DateTime DateIn { get; set; }  

In my view, I have this

                @Html.EditorFor(model => model.DateIn, "{0:yymmdd}", new { htmlAttributes = new { @class = "form-control form-control-sm datepicker"} })  

and

    <script>  
        $(document).ready(function () {  
            $('.datepicker').datepicker({  
                todayHighlight: true  
            });  
        });  
    </script>  

When I pick a date, I see date in form field as 12/19/2022. How can I change the format to 221219.

Developer technologies ASP.NET Other
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2022-12-19T21:38:56.41+00:00

    When I pick a date, I see date in form field as 12/19/2022. How can I change the format to 221219.

    The date picker library is inputting the date. Trying reviewing the documentation for the date picker you are using to see if the date picker library has this feature.

    https://api.jqueryui.com/datepicker/

     $('#datepicker').datepicker({ dateFormat: 'yymmdd' });  
    

    Keep in mind, that "mm" is minutes in .NET "MM" is month. The official date format documentation illustrates how date formats work in .NET which is separate from the date picker format.

    Custom date and time format strings

    0 comments No comments

  2. Lan Huang-MSFT 30,186 Reputation points Microsoft External Staff
    2022-12-20T03:04:08.263+00:00

    Hi @Joe Green ,

    How can I change the format to 221219.

    You need to change Datepicker's date format by:

     $(".datepicker").datepicker({  
                     dateFormat: "ymmdd",  
                     
                });  
    

    As mentioned before: "mm" is minutes in .NET and "MM" is months. If you need to display the existence date, you need to change {0:yymmdd} to {0:yyMMdd}.
    You can refer to the following example:

    public class Test  
    {  
        [DisplayFormat(DataFormatString = "{0:yyMMdd}", ApplyFormatInEditMode = true)]  
        public DateTime DateIn { get; set; }  
    }  
    

    272199-image.png

    272209-image.png

    272210-25.gif
    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.