1

I have a string variable with it's value formatted to look like "1:23:45 AM" I need to convert that into a DateTime variable for time without a date component. I am receiving an "Unhandled exception" error that is being caused by the formatting. If I remove the "AM", it works fine but the "AM/PM" component is needed for what I am trying to do. I am currently using the following code to attempt this...

"temp" is the name of the variable I am using until I come up with a more meaningful variable name...

public string PlusMinus12(string hour, string minute, string second, string ampm)
    {
        string PlusMinus;
        int rndmTmp1 = Random1();
        int rndmTmp2 = Random2();

        if (rndmTmp1 == 0)
        {
            PlusMinus = hour + ":" + minute + ":" + second + ": " + ampm;
            return PlusMinus;
        }
        else if (rndmTmp1 == 1)
        {
            string temp = hour + ":" + minute + ":" + second +": " + ampm;
            **DateTime subtract = DateTime.Parse(temp);**
            subtract.AddSeconds(-rndmTmp2);
            PlusMinus = subtract.ToString("h:mm:ss tt");
            return PlusMinus;
        }
        else
        {

DateTime subtract = DateTime.Parse(temp); is the line causing the error

The error is:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: String was not recognized as a valid DateTime.

Most of the information I have found so far on this topic include solutions that depend on the existence of the Date component, which I am not using.

Any ideas? Thank you

Sean Connelly
  • 135
  • 3
  • 13
  • 1
    Can you show what `temp` has for a value? I'm not getting any exception running your code. You need to show *all* your *relevant* code and indicate where the exception is occurring. Also, what is the actual error message? – rory.ap Dec 16 '15 at 20:30
  • Are you sure the temp string is the format you expect? It's working for me also. – doobop Dec 16 '15 at 20:37
  • Maybe this is your answer? http://stackoverflow.com/questions/9814060/how-to-convert-datetime-to-timestamp-using-c-net-ignoring-current-timezone On another note, I tried it your code converting it to string format with no problem. I would double check the format. – NKD Dec 16 '15 at 20:39
  • I have updated the code... – Sean Connelly Dec 16 '15 at 20:50

5 Answers5

3

You should try parsing it using DateTime.ParseExact using a custom format from here: Custom Date and Time Format Strings

Simon Mattes
  • 4,866
  • 2
  • 33
  • 53
0

If you're only interested in returning the time part, add a extra variable that holds the date part and append it to the front of temp when you parse it? like:

string tempDate = "2008-05-01 "
C.Chen
  • 69
  • 5
0

This works for me:

        string timeString = "1:23:45 AM";
        string format = "h:mm:ss tt";
        CultureInfo provider = CultureInfo.InvariantCulture;

        try
        {
            DateTime result = DateTime.ParseExact(timeString, format, provider);
            Console.WriteLine("{0} converts to {1}.", timeString, result.ToString());
        }
        catch (FormatException)
        {
            Console.WriteLine("{0} is not in the correct format.", timeString);
        }

Probably your issue is with a particular time.

UPDATE: You need to check you are passing minutes and seconds to this function with a 0 for values like 1-2..9. Because standard provider will not accept a string like '1:1:2 AM'.

MagisterCrazy
  • 225
  • 1
  • 10
0

public string PlusMinus12(string hour, string minute, string second, string ampm) { string PlusMinus; int rndmTmp1 = Random1(); int rndmTmp2 = Random2();

    if (rndmTmp1 == 0)
    {
        PlusMinus = hour + ":" + minute + ":" + second + ": " + ampm;
        return PlusMinus;
    }
    else if (rndmTmp1 == 1)
    {
        string temp = hour + ":" + minute + ":" + second +": " + ampm;
        DateTime subtract = DateTime.Parse("2000-01-01 " + temp);
        subtract.AddSeconds(-rndmTmp2);
        PlusMinus = subtract.ToString("h:mm:ss tt");
        return PlusMinus;
    }
    else
    {
Riad Baghbanli
  • 3,105
  • 1
  • 12
  • 20
0

Your problem is this

PlusMinus = hour + ":" + minute + ":" + second + ": " + ampm;

Change it to

PlusMinus = Int32.Parse(hour).ToString("00") + ":" + Int32.Parse(minute).ToString("00") + ":" + second.ToString("00") + " " + ampm;

A little convoluted since strings are passed in as input. No colon after the seconds and zero pad the numbers. Also, since they are input variables, at some point you should verify that they are between 0-59.

doobop
  • 4,465
  • 2
  • 28
  • 39