Link to home
Start Free TrialLog in
Avatar of zachvaldez
zachvaldezFlag for United States of America

asked on

Date without Time

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.
Avatar of Misha
Misha
Flag of Russian Federation image

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
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

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.
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-
Avatar of zachvaldez

ASKER

format should be MM/dd/yyyy.
ASKER CERTIFIED SOLUTION
Avatar of Chinmay Patel
Chinmay Patel
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@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-
@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.
I need to change the award points because other answers were equally correct. Quick click Bad fingers on my part. Sorry