user3500590
user3500590

Reputation: 11

Input string was not recognised as a valid datetime

dataRow["BookDate"] = DateTime.ParseExact(date.ToString(), @"d/M/yyyy", 
                                       CultureInfo.InvariantCulture).ToString(); 

my code is running locally but not on iis online the code is also ok with using online services as well. also added in my web.config

Upvotes: 1

Views: 139

Answers (3)

Soner Gönül
Soner Gönül

Reputation: 98868

You don't need to use DateTime.ParseExact method for this formatted string. Your string can be represented as standart date and time format. You can use just DateTime.Parse method.

Here an example on LINQPad;

var date = DateTime.Parse("05/04/2014 0:38",
                    CultureInfo.InvariantCulture);
date.Dump();

If your date is already DateTime, you don't need to do anything. If you want to string representation of it, just use DateTime.ToString method that takes string format and IFormatProvider.

date.ToString("d/M/yyyy", CultureInfo.InvariantCulture);

Upvotes: 1

Steve
Steve

Reputation: 216353

Supposing that date is a DateTime variable, all you need is a simple ToString with a format specifier

  dataRow["BookDate"] = date.ToString("d/M/yyyy");

But this raises another question, is you dataRow["BookDate"] a string field?, If yes then you really shouldn't store date in string format. You use directly DateTime fields that are indipendent from the visual format and can be correctly used when you need to apply WHERE conditions in your database queries.

Instead, if dataRow["BookDate"] is correctly a DateTime field, then you don't need any kind of formatting, you assign directly a DateTime value to this field. It is the job of the code that display that value to format it accordingly to you preferences.

Upvotes: 1

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

From Your comments if your Date Format is 05/04/2014 0:38

1 you need to use dd instead of d to represent two digit date.
2 you need to use MM instead of M for representing the two digit Month.
3 You need to use H for representing the Hour Format.
4 You need to use mm for representing the minutes Format.

Try This:

dataRow["BookDate"] = DateTime.ParseExact(date.ToString(), @"dd/MM/yyyy H:mm", 
                                   CultureInfo.InvariantCulture).ToString(); 

If you want to store only Date only.

Try This:

dataRow["BookDate"] = DateTime.ParseExact(date.ToString(), @"dd/MM/yyyy H:mm", 
                          CultureInfo.InvariantCulture).ToString("dd/MM/yyyy"); 

Upvotes: 0

Related Questions