3

I need to use

SqlDateTime.Parse(val)

where val is a string such as " 23.3.1992 00:00:00 ".

The string is in European format, that is, day precedes month. However Parse wants "American" format. How I can tell it to use particular datetime format / locale?

Thanks in advance!

onkami
  • 8,791
  • 17
  • 90
  • 176
  • 1
    Do you not have a `DateTime` instance to pass in to the database? Why use strings at all for this? – Oded May 29 '13 at 12:38
  • Why not use something totally unambigious like `YYYY-MM-dd HH:mm:ss` so `2013-05-29 13:38:00` then everything will know what it means. – Belogix May 29 '13 at 12:38
  • SqlDateTime uses the InvariantCulture. When you need something different use a DateTime and its Parse overloads where you can provide a different culture or format. And then use the SqlDateTime constructor that takes a DateTime. And like the other if possible better try to use a culture independent string format if needed. – Ralf May 29 '13 at 12:44

4 Answers4

5

Try this:

string val = "23.12.1992 00:00:00";

// Parse exactly from your input string to the native date format.
DateTime dt = DateTime.ParseExact(val, "dd.M.yyyy hh:mm:ss", null);

// Part to SqlDateTime then            
System.Data.SqlTypes.SqlDateTime dtSql = System.Data.SqlTypes.SqlDateTime.Parse(dt.ToString("yyyy/MM/dd"));

This could be done in one statement, but just separated for illustration.

Khadim Ali
  • 2,548
  • 3
  • 33
  • 61
2

Have you tried DateTime instead of SQLDateTime

DateTime d = DateTime.Parse(val); 
String s = d.ToString(CultureInfo.CreateSpecificCulture("en-US"));
Vikram Bose
  • 3,197
  • 2
  • 16
  • 33
0

Can you try this ?

string valInEuropean = "23.3.1992 00:00:00";
DateTime dateInEuropean = DateTime.Parse(valInEuropean);
string valInAmerican = dateInEuropean.ToString("yyyy-MM-dd HH:mm:ww");
Mehdi Bugnard
  • 3,889
  • 4
  • 45
  • 86
0

For converting a string to datetime object when the format is known(in this case ) use

DateTime dwweek = DateTime.ParseExact("23.3.1992 00:00:00", "dd.MM.yyyy hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
Ratna
  • 2,289
  • 3
  • 26
  • 50