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

7
  • Where did this come from? Why is it a string instead of a DateTime value? If this came from a date or datetime column, retrieve it as DateTime, don't convert it to text Commented Apr 25, 2016 at 13:04
  • it's read from a file Commented Apr 25, 2016 at 13:05
  • 1
    you should work with SqlCommand class and Parameters. or you can use this: Date.ParseExact(dateString, "yyyyddMM", provider) Commented Apr 25, 2016 at 13:06
  • Nobody asked but which part is month exactly? Commented Apr 25, 2016 at 13:08
  • 1
    @SonerGönül this looks like the unseparated date format so this is unambiguously translated to yyyyMMdd in SQL Server. Mixing up this order would show an unusual temperament on the part of the file's author. Think Hannibal Lecter. Or that guy that types � in textboxes Commented Apr 25, 2016 at 13:10

2 Answers 2

6

Try

var myResultDate = DateTime.ParseExact("20160104", 
                                       "yyyyMMdd", 
                                       CultureInfo.InvariantCulture);
Sign up to request clarification or add additional context in comments.

Comments

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);
}

1 Comment

thank you i have solve with this code

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.