texas697
texas697

Reputation: 6387

How to parse a angular-ui dateTime string to c# datetime

I know a lot of questions about this has been answered. I have tried for about 3 hours with no luck. I am using angular-ui datetime picker, the format is

"2015-02-08T06:00:00.000Z"

Error message is string was not recognized as a datetime

at System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style) at System.DateTime.ParseExact(String s, String format, IFormatProvider provider) at TransparentEnergy.Controllers.apiDocumentController.d__2.MoveNext() in c:\Development\TransparentEnergy\TransparentEnergy\ControllersAPI\apiDocumentController.cs:line 67

Controller

 string docDate = provider.FormData["DocumentDate"];
 model.DocumentDate = DateTime.ParseExact(docDate, "yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.GetCultureInfo("en-US"));

Angular-UI

 $scope.open = function ($event) {
    $event.preventDefault();
    $event.stopPropagation();

    $scope.opened = true;
};
$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
$scope.format = $scope.formats[3];

Update

 string docDate = provider.FormData["DocumentDate"];
            model.DocumentDate = DateTime.ParseExact(docDate, "yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);

Upvotes: 0

Views: 6025

Answers (3)

Peter M.
Peter M.

Reputation: 1088

Try this format

yyyy-MM-dd'T'HH:mm:ss.fff'Z'

  var date = DateTime.ParseExact("2015-02-08T06:00:00.000Z", "yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture);

Upvotes: 0

Ravi M Patel
Ravi M Patel

Reputation: 3035

Is there any specific reason why you are not using DateTime.Parse()?

The format you have specified "2015-02-08T06:00:00.000Z" is ISO date time format. refer to http://en.wikipedia.org/wiki/ISO_8601

The one you have shown is UTC time and when you use

DateTime.Parse("2015-02-08T06:00:00.000Z")

you get local date-time. According to the timezone of the server \ pc you are running code on.

You can use

DateTime.Parse("2015-02-08T06:00:00.000Z").ToUniversalTime()

to get UTC. Does it help?

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499860

Look at the format you're passing:

"yyyy-MM-dd'T'HH:mm:ss'Z'"

That has no milliseconds, whereas your sample is "2015-02-08T06:00:00.000Z" which does have milliseconds. It looks like you want:

"yyyy-MM-dd'T'HH:mm:ss.fff'Z'"

Also, I'd suggest using CultureInfo.InvariantCulture rather than the US culture - they'll both work the same in this case, but I think it's clearer to use the invariant culture when you're basically talking about a machine-to-machine format.

You should also include DateTimeStyles.AssumeUniversal to take account of the Z.

Upvotes: 0

Related Questions