AliK
AliK

Reputation: 1067

C# Date Parse non standard date format

Get a strange date format from web service and am wondering how to parse it to a normal datetime.

Service result: 01-05T09:55 (MM-dd Time)

As this string does not have year it fails in DateTime.Parse.

Any ideas how to get it to the current year without manipulating it with string functions?

Upvotes: 2

Views: 546

Answers (2)

Mata Prasad Chauhan
Mata Prasad Chauhan

Reputation: 552

You can use below format;

var date = "01-05T09:55";
var dateTime = DateTime.ParseExact(date, "MM-ddTHH:mm", CultureInfo.InvariantCulture);
Console.WriteLine(dateTime);

Here is a working example;

https://dotnetfiddle.net/S2nz1N

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Try DateTime.ParseExact and provide the format:

string source = "01-05T09:55";

// 5 Jan 2017 (current year) 9:55
DateTime result = DateTime.ParseExact(source, "M-d'T'H:m", CultureInfo.InvariantCulture);

Upvotes: 5

Related Questions