简体   繁体   中英

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

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?

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM