i want to format date time value in this format (“yyyy/MM/dd”)
below is the code, m using to do so
DateTime? date = DateTime.Now;
DateTime? formattedDate = Convert.ToDateTime(date.Value.ToString("yyyy/MM/dd"));
Console.WriteLine(formattedDate);
Console.ReadLine();
the code work fine but you can see in the above code that i have declared datetime variable as null which in reverse causing the problem
please suggest what i am doing wrong in the above code.
as i am getting the output as this 9/10/2012 12:00:00 AM
Thanks,
Aaman
The problem is that what you call
formattedDateis actually yet another instance of a DateTime. There’s no notion of format inside the native .NET DateTime structure. You can talk about formatting only when you convert it to a string:or if you want to use a nullable DateTime:
But since your question is tagged with
asp.net-mvc-3, there are other ways to format values. For example using the[DisplayFormat]attribute on your view model:and in your view if you want to display the value of your view model:
or if you want to generate an input field with properly formatted value: