开发者

VB.NET - any string to date conversion

Short question. I am 开发者_JS百科trying to convert a string into Date (to put it later into INSERT command). My problem is that the string I am reading is always different (there is no rule what format it is going to be - as this is user-dependent).

I found such piece of code on the stackoverflow:

DateTime myDate = 
    DateTime.ParseExact("2009-05-08 14:40:52,531", 
                        "yyyy-MM-dd HH:mm:ss,fff",
                        System.Globalization.CultureInfo.InvariantCulture)

but in my case it will not work as I don't know what kind of format I am going to import. Is there any universal import function which checks all known formats? If now how should I write it? (please give me some hints).

Thanks for any tips and hints in advance, Pete


If you don't (or can't) validate the date as the user enters it (to ensure it is a valid date), then you're kind of screwed.

Taking locals into account, 1/2/2011 could be 1st Feb (Ireland, UK & Europe), or could be 2nd Jan (USA).

Even ignoring locals it can get hairy, some one puts in "Thursday 13/10/11", the 13th is Thursday fine, what if they get it wrong and put in "Friday 13/10/11", or they just put Friday 10/11, is that today (Friday 14th Oct 2011) or some Friday in November 2011.

Then you get the intuitive user that enters "Next Thursday", in theory you can handle that too, should you?

Then you get typos, 112//2011, is that 11/2/2011, or 1/12/2011?

There's too much going wrong here, do whatever you need to do to ensure the user input is valid, move heaven and earth if you must, but do this where the user enters the data.


No this is not possible however you may define possible formats in an array and pass it to ParseExact or TryParseExact method.

Dim format() As String = {"dd-MM-yy", "dd/MM/yy"}

Dim myDate As DateTime = DateTime.ParseExact("2009-05-08 14:40:52,531",format, 
                      System.Globalization.CultureInfo.InvariantCulture))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜