Date without Time

zachvaldez
zachvaldez used Ask the Experts™
on
I'd like to remove the time portion from this code...
 lbllastseen.Text = dr["Lastseen"].ToString();

Open in new window


Currently it displays the date and time.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Try this code:
YourDateTime.ToString("dd/MM/yyyy")

Open in new window

if the format is always the same (unfortunately the label is TEXT instead of TIME format) you could use LEFT and the char count, to only get the date.

regards
Thomas

Commented:
If you get not DateTime variable, you can convert to DateTime and then display in this format:
Convert.ToDateTime(dr["Lastseen"]).ToString("dd/MM/yyyy");

Open in new window

Build an E-Commerce Site with Angular 5

Learn how to build an E-Commerce site with Angular 5, a JavaScript framework used by developers to build web, desktop, and mobile applications.

Chinmay PatelChief Technology Ninja
Distinguished Expert 2018

Commented:
Hi Zachvaldez,

I am not sure about the original format of your date hence, try this:

DateTime lastSeen = DateTime.MinValue;
            if(DateTime.TryParse( dr["Lastseen"].ToString(), out lastSeen))
            {
                Console.WriteLine(lastSeen.ToShortDateString());
            }
            else
            {
                Console.WriteLine("Error in Input Date");
            }

Open in new window


Regards,
Chinmay.

Commented:
Either solution by Misha or Chinmay would work.  That being said, you would want to include a null check or null-conditional check as the datarow value could potentially be null; e.g. -
var converted = default(DateTime);
if (DateTime.TryParse(dr["LastSeen"]?.ToString(), out converted))
{
	Console.WriteLine(converted.ToShortDateString());
}
else
{
	Console.WriteLine("Error in Input Date");
}

Open in new window

-saige-

Author

Commented:
format should be MM/dd/yyyy.
Chief Technology Ninja
Distinguished Expert 2018
Commented:
Hi zachvaldez,

Just change to
Console.WriteLine(lastSeen.ToString("MM/dd/yyyy"););

Open in new window


@it_saige,
Wouldn't TryParse take care of null value? :)

Regards,
Chinmay.

Commented:
@Chinmay,

TryParse does indeed take care of a null value, however, a NullReferenceException would be thrown if you try to use ToString() on a null.

-saige-
Chinmay PatelChief Technology Ninja
Distinguished Expert 2018

Commented:
@it_saige,
Yes. My bad. ToString indeed will throw an exception. Please use

@zachvaldez,
dr["LastSeen"]?.ToString()

Open in new window


Or

dr["LastSeen"] as string

Open in new window


to avoid it.

Regards,
Chinmay.

Author

Commented:
I need to change the award points because other answers were equally correct. Quick click Bad fingers on my part. Sorry

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial