0

I am doing an asp.net mvc project and I need to convert the string of "06/22/2019 00:00:00" to a valid DateTime type in format of 2019/06/22 without the part of hour and minute and second

SalShah
  • 33
  • 1
  • 6
  • This kind of questions show up regularly. There is no variable of type DateTime without the Time part. It is how do you format the variable for display that matters here. So if you want to display only the date then _date.ToString("yyyy/MM/dd")_ and now you have a string to display that appears to an human being as a date only – Steve Jun 27 '19 at 09:58

4 Answers4

1

You can use DateTime.ParseExact, here is an example :

http://net-informations.com/q/faq/stringdate.html

Finally, it should look like this :

string s = "06/22/2019 00:00:00";
DateTime myDate = DateTime.ParseExact(s, "MM/dd/yyyy HH:mm:ss",System.Globalization.CultureInfo.InvariantCulture);
Debug.WriteLine(myDate.ToString("MM/dd/yyyy"));
lema
  • 470
  • 2
  • 9
0

You can do this:

var dateString = "06/22/2019 00:00:00";
var datePart = dateString.Split(' ')[0];
var date = DateTime.Parse(datePart);

Though remember that DateTime will still have a default value for the time (12:00 AM), if you want the Date part only from the object, use date.Date which will return an instance with the default time (mentioned earlier).

Anton Kahwaji
  • 427
  • 6
  • 12
  • 1
    Hello. Thank you. The code of (var datePart = dateString.Split(' ')[0]) will return me "06/22/2019" and in code of (var date = DateTime.Parse(datePart);) will return me the error ( String was not recognized as a valid DateTime) – SalShah Jun 27 '19 at 10:07
  • That's not true at all, here you can see for yourself https://dotnetfiddle.net/7Fc2C0 – Anton Kahwaji Jun 27 '19 at 15:16
0

You convert the string to a DateTime object and then to display just the date portion you can use ToShortDateString like this:

var myDateTime = DateTime.Parse( "06/22/2019 00:00:00") //presumably use a variable here instead.
var date = myDateTime.ToShortDateString();

How you want to display this can be done using the CultureInfo part as shown here: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.toshortdatestring?view=netframework-4.8

sr28
  • 3,717
  • 4
  • 29
  • 49
0

DateTime contains default Time even if you access DateTime.Date. You can achieve format of date by converting Date into string.

Something like,

    DateTime myDate = DateTime.ParseExact("06/22/2019 00:00:00", "MM/dd/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
    string dateInFormat = $"{myDate.Year}/{myDate.Month}/{myDate.Day}";

POC : .net Fiddle

Prasad Telkikar
  • 10,243
  • 2
  • 12
  • 31