Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert datetime to short date?

i have a table called as X and this table has a field known as X_DateTime respectively, which has value like 2012-03-11 09:26:37.837.

i want to convert the above datetime value to this format yyyy-MM-dd (2012-03-11) and literally remove the Time (09:26:37.837)

i have used something like below code

DateTimeFormatInfo format = new DateTimeFormatInfo();
format.ShortDatePattern = "yyyy-MM-dd";
format.DateSeparator = "-";
DateTime date = 2012-03-11 09:26:37.837;
DateTime shortDate = Convert.ToDateTime(date , format);

please help me...

i am using C# as my language.

thanks,

like image 911
aamankhaan Avatar asked Apr 03 '12 05:04

aamankhaan


2 Answers

DateTime dateToDisplay = new DateTime(2014, 11, 03, 42, 50);
String shortDateTime = dateToDisplay.ToShortDateString();

Then you can convert this shortDateTime to datetime like this

DateTime shortDate = Convert.ToDateTime(shortDateTime);
like image 116
amnippon Avatar answered Nov 17 '22 05:11

amnippon


You must call .ToString() method with that format that you want. In your example it will be like this.

DateTime date=DateTime.Now;
var shortDate=date.ToString("yyyy-MM-dd");

Or if you want to keep DateTime type, you must call .Date property of DateTime

DateTime date=DateTime.Now;
var shortDate=date.Date;

From MSDN

A new object with the same date as this instance, and the time value set to 12:00:00 midnight (00:00:00).

like image 36
Chuck Norris Avatar answered Nov 17 '22 06:11

Chuck Norris