Home > Blockchain >  TryParseExact / ParseExact in .net to match this date time 2021-03-04T17:00:0s.000Z
TryParseExact / ParseExact in .net to match this date time 2021-03-04T17:00:0s.000Z

Time:12-20

Can anyone help me work out what the Patten would be to match this date time

2021-03-04T17:00:0s.000Z

var dateValue = "2021-03-04T17:00:0s.000Z";
string pattern = "yyyy-MM-dd'T'hh:mm:s's'.fff'Z'";
DateTime parsedDate;

var datetime = DateTime.TryParseExact(dateValue, pattern, null,
    DateTimeStyles.None, out parsedDate);

This is my attempt but its not working.

Thanks for any help

CodePudding user response:

This should work:

string pattern = "yyyy-MM-dd'T'HH:mm:s's'.fff'Z'";

But anyways, this is not a part of any date time standard. You should fix the source of this datetime string. It has a bug.


UPDATE

Another way to fix it is to replace the s character with a 0:

var dateValue = "2021-03-04T17:00:0s.000Z".Replace('s', '0');
var parsedDate = DateTime.Parse(dateValue);

UPDATE

Here is a method to fix the string event if there is gonna be two numbers before s:

DateTime ParseCorruptedTime(string dateValue) {
    dateValue = dateValue.Replace("s", "");
    var colonIndex = dateValue.LastIndexOf(':');
    var dotIndex   = dateValue.LastIndexOf('.');
    if (dotIndex - colonIndex < 3) {
        dateValue = dateValue.Insert(colonIndex   1, "0");
    }
    return DateTime.Parse(dateValue);
}
var dateValue1 = "2021-03-04T17:00:5s.000Z";
var dateValue2 = "2021-03-04T17:00:56s.000Z";
var parsedDate1 = ParseCorruptedTime(dateValue1);
var parsedDate2 = ParseCorruptedTime(dateValue2);

This will produce the following output:

parsedDate1: 2021-03-04T17:00:05.000Z
parsedDate2: 2021-03-04T17:00:56.000Z
  • Related