简体   繁体   中英

Parse hour and AM/PM value and add to existing time

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.

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM