Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract date part from a datetime in vb.net

I have a sql query which extract a field of datatype smalldatetime. I read this field using datareader, convert it to string and store it in a string variable.

I get the string as 1/1/2012 12:00:00 AM ,here i want to use only date part of this string and i have nothing to do with the time.

How can i cut only the date from the string and get the output as 1/1/2012?

like image 727
Ishan Avatar asked Dec 30 '11 10:12

Ishan


3 Answers

You may convert string to date type using Date.Parse() and use ToShortDateString()

Dim dt as Date = Date.Parse(dateString)
Dim dateString=dt.ToShortDateString()

As you said the type of field is smalldatetime then use DataReader.GetDateTime(column_ordinal).ToString("d") method or DataReader.GetDateTime(column_ordinal).ToShortDateString()

like image 117
KV Prajapati Avatar answered Sep 24 '22 14:09

KV Prajapati


You need to format the DateTime using a format string for only dates.

string dateString = myDate.ToString("d");

This is equivalent to:

string dateString = myDate.ToShortDateString();
like image 30
Oded Avatar answered Sep 26 '22 14:09

Oded


You can convert the string to Date and then get the Date part of the variable:

Dim myDateTime as Date = Date.Parse(dateString)
Dim MyDate as Date = myDateTime.Date()
like image 33
Pedro Francisco Pereira Avatar answered Sep 26 '22 14:09

Pedro Francisco Pereira