0

I'm trying below code to try to parse time and add it to current date:

string[] sDatetimeFormat1 = { "M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
                             "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
                             "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
                             "M/d/yyyy h:mm", "M/d/yyyy h:mm",
                             "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm" };
string[] sDatetimeFormat2 = { "HH:mm tt", "h:m t", "HH:mm:ss",
                             "HH:mm:ss tt", "h:m:s t"};

if (DateTime.TryParseExact(InputDateOrTime.Replace("\"", ""), 
    sDatetimeFormat1, new CultureInfo("en-US"), DateTimeStyles.None, 
    out sStartTime))
{
    //something
}
else if (TimeSpan.TryParse(InputDateOrTime.Replace("\"", ""), out tsInput))
{
    sStartTime = DateTime.Parse(DateTime.Today.ToString() + tsInput);
}

Input might appear as in sDateTimeFormat1 or might as well appear as in sDatetimeFormat2, If it's sDatetimeFormat1 then I need to just parse it. If it's as in sDatetimeFormat2, then I need to add that time to current date.

Ex: "06/03/2016 14:22:00" should be parsed as "06/03/2016 2:22:00 PM"

"2:22 PM" should be parsed as "06/03/2016 2:22:00 PM" (i.e., today + timespan: format is not important, but it should represent the same date-time).

.Net version is 2.0

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Rookie Programmer Aravind
  • 11,952
  • 23
  • 81
  • 114

1 Answers1

0

There are a few problems in the code you provided. The first one is that you try to parse a string representing time as a TimeSpan object. TimeSpan does not represent time, it rather represents a time difference, e.g. 2 hours.

The second problem is that you didn't include the right formatter for the string you showed. It should be "h:mm tt" or simply "t".

The following code does the conversion you wanted:

string[] sDatetimeFormat2 = { "HH:mm tt", "h:m t", "HH:mm:ss",
                         "HH:mm:ss tt", "h:m:s t", "H:mm tt", "h:mm tt"};

DateTime tsInput;
var InputDateOrTime = "2:22 PM";
DateTime.TryParseExact(InputDateOrTime.Replace("\"", ""), sDatetimeFormat2, new CultureInfo("en-US"), DateTimeStyles.None,  out tsInput);
Console.WriteLine(tsInput);

Notice that you don't need to add the current date because DateTime.TryParseExact does it for you. The output for this example is 6/3/2016 2:22:00 PM.

Tomer
  • 1,606
  • 12
  • 18