-5

Hello I want to convert string to DateTime. My string is like this '2016/11/18/12/03'.2016 is year,11 is month 18 is a day 12 hour and 3 min. I want to convert it into format like this '2016-11-18 12:03:00.000'. How can do that in C#? Can I use split function which form array. That split yyyy, month, date, hh and min. How to add them to form new date?

string s = '2016/11/18/12/03'
string[] arr = s.split('/');
diiN__________
  • 7,393
  • 6
  • 42
  • 69
Jui Test
  • 2,399
  • 14
  • 49
  • 76
  • Lookup DateTime.ParseExact https://msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx and Custom Date Format String https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx – Martheen Nov 18 '16 at 07:30
  • See [this answer](http://stackoverflow.com/a/3373348/993547). – Patrick Hofman Nov 18 '16 at 07:30

3 Answers3

2

the below should work -

using System.Globalization;

DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
string dateString = "yyyy/MM/dd/HH/mm";
result = DateTime.ParseExact("2016/11/18/12/03", dateString, provider);
//2016-11-18 12:03:00.000
string display = result.ToString("yyyy-MM-dd HH:mm:ss.fff");
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
jokerday
  • 136
  • 1
  • 10
1

Use DateTime.ParseExact to turn the string into a DateTime and then turn it into a string by calling dteTime.ToString passing the required output format.

DateTime dateTime = DateTime.ParseExact(myString, "yyyy/MM/dd/HH/mm", CultureInfo.InvariantCulture);
string output = dateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
Emond
  • 50,210
  • 11
  • 84
  • 115
0
string s = "2016/11/18/12/03"

DateTime dt = DateTime.ParseExact(s, "yyyy/MM/dd/HH/mm", CultureInfo.InvariantCulture);

string s2 = dt.ToString("yyyy-MM-dd HH:mm:ss.fff");
Hannott
  • 106
  • 5