2

Similar question like the already one Parse hour and AM/PM value from a string - C# but i need some thing like this.

string input = "9:00 PM";
DateTime currentTime = DateTime.Now;
// Resultant time like this
currentTime.Add(input)   // Just a sudo

If current datetime like 9/6/2013 3:18 AM then result would be like this 9/6/2013 9:00 PM How to achieve this. Thanks in advance.

Community
  • 1
  • 1
Muhammad Umar
  • 3,761
  • 1
  • 24
  • 36

2 Answers2

4

This will do the trick...

string input = "9:00 PM";
DateTime time = DateTime.Parse(input);

Outputs present date with the input time.

9/6/2013 9:00 PM

Naren
  • 2,231
  • 1
  • 25
  • 45
2

Try like this;

string input = "9:00 PM";

if (input.IndexOf("PM") > 0)
{
     DateTime dt = DateTime.Today.Date;
     int hour = Int32.Parse(input[0].ToString()) + 12;
     TimeSpan ts = new TimeSpan(0, hour, 0, 0, 0);
     Console.WriteLine(dt.Add(ts));
}

Output will be;

06.09.2013 21:00:00

Here a DEMO.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364