2

I have a String that looks like

4/2/2012 12:00 AM
12/30/1899 10:00 AM

I want to format the strings so the first date/time stamp looks like

4/2/2012

The second should look like

10:00 AM

SHould I use the whitespace as a means to split the string?

5 Answers 5

7

For complete string -->

string s= DateTime.Parse("4/2/2012 12:00 AM").ToString("d/M/yyyy hh:mm tt");

For separated strings -->

string date=DateTime.Parse("4/2/2012 12:00 AM").ToString("d/M/yyyy");
string time = DateTime.Parse("4/2/2012 12:00 AM").ToString("hh:mm tt");
Sign up to request clarification or add additional context in comments.

2 Comments

Worth looking at DateTime.TryParse also - nice if the input strings are not guaranteed to be properly formatted. Returns true if the parse was successful.
string date=DateTime.Parse("4/2/2012 12:00 AM").ToString("d/M/YYYY"); should be string date=DateTime.Parse("4/2/2012 12:00 AM").ToString("d/M/yyyy");
1

use the following function:

     string dstr = "4/2/2012 12:00";        
     DateTime dtime=Convert.ToDateTime(dstr )
     string dt1 = dtime.ToShortDateString();//to get the date
     string dt2 = dtime.ToShortTimeString();//to get the time

Comments

1

Have a look here
Just add .Tostring("") and between the "" you add the pattern, as shown at the site

1 Comment

Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
1
DateTime dt;
if (DateTime.TryParse("4/2/2012 12:00 AM",dt))
{
  String Result = "";
  if (DateTime.Date > DateTime.MinValue)
    Result = dateTime.ToString("d/M/YYYY");
  if (DateTime.TimeOfDay > TimeSpan.MinValue)
    Result += dateTime.ToString("hh:mm tt");
}

Comments

0
DateTime foo = DateTime.Parse("4/2/2012 12:00 AM");
string date = foo.ToShortDateString();
string time = foo.ToShortTimeString();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.