1

Hello I have a String of this type: 20160104 I should convert it into format of SqlServer datetime with c#, how can I do? I have try with this:

DataUltimaVariazione = Convert.ToDateTime("20160104");

but visual studio give me an error

Gerald Schneider
  • 17,416
  • 9
  • 60
  • 78
rikideveloper
  • 21
  • 1
  • 6

2 Answers2

6

Try

var myResultDate = DateTime.ParseExact("20160104", 
                                       "yyyyMMdd", 
                                       CultureInfo.InvariantCulture);
MusicLovingIndianGirl
  • 5,909
  • 9
  • 34
  • 65
2

You can use DateTime.ParseExact (https://msdn.microsoft.com/de-de/library/system.datetime.parseexact(v=vs.110).aspx) to convert a string to datetime:

DateTime dateTime = DateTime.ParseExact("20160104", "yyyyMMdd",
CultureInfo.InvariantCulture);

You could also use DateTime.TryParseExact (https://msdn.microsoft.com/de-de/library/h9b85w22(v=vs.110).aspx) which gives you more control on wrong formatted datetime strings:

DateTime dateTime;
if (DateTime.TryParse("20160104", "yyyyMMdd",
CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
    Console.WriteLine(dateTime);
}
Norman
  • 3,279
  • 3
  • 25
  • 42