0

I am having a problem with a DateTime string not being recognized. With our licensing program, you generate a key which has an expiration DateTime associated with it. However, some of our customers in another part of the world are unable to apply this key, and the error which comes back is "String was not recognized as a valid DateTime".

I looked at the key which I sent them and after decrypting it, the DateTime looks fine to me. Is there a discrepancy with how DateTimes are formatted in different parts of the world that I need to take into account? (Right now I am under the assumption that .NET will just "figure it out", which I'm thinking might not be the case now) And if so, how would I go about formatting our DateTime so that it works in any part of the world?

EDIT Here is the DateTime string: "10/16/2122 4:36:17 PM"

codewario
  • 19,553
  • 20
  • 90
  • 159

3 Answers3

3

Spontaneously I would try to use the .ToString() method to apply a custom format.

Example:

string date = DateTime.Now.ToString("yyyy-MM-dd"); // International standard

You can follow the MSDN Custom Date and Time Format help to format it the way you need.

einord
  • 2,278
  • 2
  • 20
  • 26
2

My guess is that your key is generated like this:

string key = date.ToString();

This will give a different result for different country.
Make the key uniquely generated by giving a fix format:

string key = date.ToString("yyyyMMdd");

Then you can parse it back to a date in all country:

var date = DateTime.ParseExact(key, "yyyyMMdd", CultureInfo.InvariantCulture);

Further reading here.
And here you can find all the date format you have ever dream of.

Community
  • 1
  • 1
Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122
  • Yeah, this is how I'm converting the DateTime to a string (the top one). I'm gonna give this a go and see how it works using the InvariantCulture. I always figured DateTime.ToString() was consistent across different countries, never really looked at the DateTime API other than for formatting help. – codewario Apr 11 '13 at 14:46
2

It's probably a culture issue. Use InvariantCulture to make sure you always use the same format

string datestring  = DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture)

DateTime date = DateTime.Parse(datestring, System.Globalization.CultureInfo.InvariantCulture);
Rik
  • 28,507
  • 14
  • 48
  • 67