Pankaj
Pankaj

Reputation: 10095

current date format

Is there any way to find the current format of date in the time zone? I am retrieving date in the form of string from database and in case the current datetime format does not match, crash comes, "String was not recognized as valid datetime"

Upvotes: 0

Views: 159

Answers (3)

pjvds
pjvds

Reputation: 956

The DateTime.Parse method uses the format that is set on the executing thread. See the Thread.CurrentCulture to retrieve the CultureInfo that use used when parsing. The CultureInfo.DateTimeFormat returns the format you are looking for.

If you know the format, you should use the DateTime.ParseExact method to parse the input string with a known format.

Upvotes: 0

Simon Stender Boisen
Simon Stender Boisen

Reputation: 3431

Sound like you need to use the DateTime.TryParse-method:

http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx

If you don't know in which format the date is passed and .NET can't figure it out I think your out of luck. You could of cause try to see if you could figure out the format by yourself by using regex.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500525

It sounds like what's important isn't the current format of the date as your code understand it, but as it gets it from the database. Why is it in the database as a string to start with? If at all possible you should make it an appropriate date/time related field in the database and make the driver do the conversion.

If that's not possible, you should perform the conversion in your code using a custom date/time format which matches what the server gives you, and in an appropriate culture (quite possibly the invariant one).

Upvotes: 5

Related Questions