Format string as short date

  • Thread starter Thread starter moondaddy
  • Start date Start date
M

moondaddy

using c#3.5, how do I take a string which contains a data, and format it as
a short data format like this:

"2/5/2008 1:17:11 AM"

and format to:

"02/05/2008"

Thanks.
 
using c#3.5, how do I take a string which contains a data, and format it
as
a short data format like this:

"2/5/2008 1:17:11 AM"

and format to:

"02/05/2008"

Well, one way would be to use the DateTime.TryParse() method to convert
the string to a DateTime object, and then use the
DateTime.ToShortDateString() to reformat the data into the the string you
want.

Pete
 
MoonDaddy,

First check the globalization settings are US then just

\\\

var date = DateTime.Parse("5/2/2008 1:17:11").ToShortDateString();

///



I have done it in my globalisation settings.

Cor
 
Well, first you would parse the original string into a DateTime
instance. I would call TryParse, passing the general date time pattern "g"
(assuming that your culture is "en-us").

Because the generat date time pattern is dependent on the current
culture information to determine the format of the general date/time
pattern, if you want to use an exact pattern, you would use:

d/M/yyyy h:mm:ss tt

Of course, even the above is subject to culture info, in that the AM/PM
designator is specific to the DateTimeFormatInfo on the current culture.
You would probably want to make sure that the invariant culture is used when
parsing.

Then, once you have the DateTime instance, you can call ToString on it,
passing a format of:

dd/MM/yyyy

For your output.
 
Hi,

You have to convert the string to DateTime and then use
DateTime.ToShortDateString();

Take a lookat DateTime.TryParse or Convert.ToDateTime
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top