5

If I have theses general sql valid dates in c# strings :

(each date can be in different order inside ) e.g. :

01 feb 2010
feb 01 2010
2010 01 feb
...
...

I want to convert a string date to DateTime(c#). ( i want the ability to convert every format from above list)

while parse exact requires me 3! combinations , is there any better solution ?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • 1
    3! is only 6... However, you could just split on space, and figure out whether each chunk is alphas, 4 digits, or 2 digits... Btw - how does this relate to SQL? – Marc Gravell Jul 01 '12 at 10:15
  • yeah i know , thats what ive strted to do... but again before i continue , just checking if other solution – Royi Namir Jul 01 '12 at 10:16
  • 4 digits for year, 3 chars for months, 2 digits for day. You could use a regex with matching groups and do a single parse exact. – David Brabant Jul 01 '12 at 10:16
  • 1
    Sure you wont get "Feb" as 02? THEN you are dead. – TomTom Jul 01 '12 at 10:16
  • @MarcGravell sql will _always_ know how to parse this format. nomatter the location of each argument. the datepicker stores the valu in the textbox as this format , and later in c# - i need to translate it to c# datetime. – Royi Namir Jul 01 '12 at 10:34

1 Answers1

2

I think i got it ... enter image description here

string[] str = new[] { "01 feb 2010","feb 01 2010","2010 01 feb","2010 feb 01","feb 2010 01" };
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");                       
for (int i = 0; i < str.Length; i++)
{
    DateTime t = DateTime.Parse(str[i], culture);
    t.Dump();
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • 1
    No need to set (pollute) the `CurrentThread.CurrentCulture`. `Parse(..., culture)` should be enough. – H H Jul 01 '12 at 10:28
  • @HenkHolterman yep...although when i display it DOES change the order ( my computer is at dd/MM/yyyy ) so it shows me : 01/02/2010 ....but just for display (which is irrelevant) – Royi Namir Jul 01 '12 at 10:32
  • 2
    @abatishchev its like Console.Writeline in Linqpad. http://www.linqpad.net/ (great tool - youll love it) – Royi Namir Jul 01 '12 at 12:36