0

I need to convert a value to a C# DateTime.

Data looks like below:

20161021-12:55:16.000

20161021-13:22:09.974

I tried

 String dtTime = "20161021-13:22:09.974";
 dtTime = dtTime.Replace("-"," ");

 DateTime outPut = Convert.ToDateTime(dtTime);

and it throws an error.

Can I get help to convert these samples into a valid date time?

Also these values are in UTC.

I need to convert them to EST.

Appreciate your help.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Vikas Kunte
  • 683
  • 4
  • 15
  • 35
  • 2
    Please bear in mind that "it throws an error" is considered a repulsive phrase on this site. I doubt the specifics in this case bear relevance to answers, but it's good practice to specify the error thrown. – Alex F Dec 27 '16 at 14:22

2 Answers2

4

You need to use DateTime.ParseExact with your specific format.

Check out this: https://msdn.microsoft.com/es-es/library/w2sa9yss(v=vs.110).aspx

For the eastern time conversion, try something like this (replace DateTime.Now with your date):

var timeUtc = DateTime.UtcNow;
TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime easternTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, easternZone);
NicoRiff
  • 4,803
  • 3
  • 25
  • 54
0

I would use TryParseExact:

String dtTime = "20161021-13:22:09.974";

DateTime outPut;
if (DateTime.TryParseExact(dtTime, "yyyyMMdd-HH:mm:ss.fff", null, DateTimeStyles.None, out outPut))
{
    var est = TimeZoneInfo.ConvertTimeFromUtc(outPut,
                            TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
    Console.WriteLine(est);
}
Cetin Basoz
  • 22,495
  • 3
  • 31
  • 39