user9452014
user9452014

Reputation: 13

Parse string to DateType ASP.NET C# exception - The string was not recognized as a valid DateTime

So I have a date which is in this format. My goal is to add 7 days to this string startdate and post it into a database as a string. However, I have to convert it to datetime to allow me to add days to it. I am reading startdate from a database but this is what it looks like.

string startdate = "10-03-2018 03:15PM";

IFormatProvider culture = new CultureInfo("en-US", true);
DateTime starttime2 = DateTime.ParseExact(startdate, "MM/dd/yyyy HH:mm tt", culture); 

// It is breaking on the above line with the error - The string was not recognized as a valid DateTime.

DateTime endtime2 = starttime2.AddDays(+7);

Anyone able to help me solve this issue? I am new to C# and would appreciate any help at all..

Thank you

Upvotes: 0

Views: 73

Answers (3)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

You have specified wrong format actually. You should be specifying the following format:

"dd-MM-yyyy hh:mmtt"

as your date is in format :

"10-03-2018 03:15PM"

Assuming that the first number us for day and second is for month, otherwise you can swap those.

You can see more details on the usage of ParseExact here.

Upvotes: 3

Oleksii Klipilin
Oleksii Klipilin

Reputation: 1936

Try this:

    string startdate = "10-03-2018 03:15PM";

    IFormatProvider culture = new CultureInfo("en-US", true);
    DateTime starttime2 = DateTime.ParseExact(startdate, "dd-MM-yyyy hh:mmtt", culture);

no space between mm and tt. also this is 12 hours format so hh

Upvotes: 1

Mihir Dave
Mihir Dave

Reputation: 4014

I think this will help you

    public static DateTime AddDaysToMyDate(string date)
    {
        return DateTime.ParseExact(date, "dd-MM-yyyy hh:mmtt", new CultureInfo("en-US", true)).AddDays(7);
    }

Use it as

DateTime newDateTime = AddDaysToMyDate("10-03-2018 03:15PM");

Upvotes: 0

Related Questions