{"record":{"id":"426525b09747f346","repo":"OrchardCMS/OrchardCore","slug":"cannot-convert-value-to-datetime","errorCode":null,"errorMessage":"Cannot convert {value} to DateTime","messagePattern":"Cannot convert (.+?) to DateTime","errorType":"exception","errorClass":"InvalidCastException","httpStatus":null,"severity":"error","filePath":"src/OrchardCore/OrchardCore.Abstractions/Json/Dynamic/JsonDynamicValue.cs","lineNumber":307,"sourceCode":"    {\n        return value?._jsonValue?.GetValue<byte?>();\n    }\n\n    public static explicit operator char(JsonDynamicValue value)\n    {\n        return value?._jsonValue?.GetValue<char>()\n            ?? throw new InvalidCastException($\"Cannot convert {value} to Char\");\n    }\n\n    public static explicit operator char?(JsonDynamicValue value)\n    {\n        return value?._jsonValue?.GetValue<char?>();\n    }\n\n    public static explicit operator DateTime(JsonDynamicValue value)\n    {\n        return value?._jsonValue?.GetValue<DateTime>()\n            ?? throw new InvalidCastException($\"Cannot convert {value} to DateTime\");\n    }\n\n    public static explicit operator DateTime?(JsonDynamicValue value)\n    {\n        return value?._jsonValue?.GetValue<DateTime?>();\n    }\n\n    public static explicit operator DateTimeOffset(JsonDynamicValue value)\n    {\n        return value?._jsonValue?.GetValue<DateTimeOffset>()\n            ?? throw new InvalidCastException($\"Cannot convert {value} to DateTimeOffset\");\n    }\n\n    public static explicit operator DateTimeOffset?(JsonDynamicValue value)\n    {\n        return value?._jsonValue?.GetValue<DateTimeOffset?>();\n    }\n","sourceCodeStart":289,"sourceCodeEnd":325,"githubUrl":"https://github.com/OrchardCMS/OrchardCore/blob/4306c0717fe573f6fca1b4955909ddab6a192807/src/OrchardCore/OrchardCore.Abstractions/Json/Dynamic/JsonDynamicValue.cs#L289-L325","documentation":"JsonDynamicValue wraps a JSON value and exposes explicit cast operators to .NET primitives. The explicit operator DateTime casts via JsonValueExtensions.GetValue<DateTime>(); when the cast target is null (null wrapper) or the underlying JSON value cannot be represented as a DateTime, the operator throws InvalidCastException with this message. It exists to give a clear diagnostic instead of an opaque null-reference or conversion failure.","triggerScenarios":"Executing `(DateTime)jsonDynamicValue` (via dynamic dispatch or direct cast) where the wrapper is null or its _jsonValue is null, or where the JSON token is a non-date value (plain string not parseable as DateTime, number, boolean, object, array).","commonSituations":"Reading JSON property bags (content item JSON, workflow inputs, query results) where a field is expected to be a date but is null, absent, or stored as an arbitrary string; schema changes that turn a date field into text; hand-edited JSON data.","solutions":["Verify the underlying JSON token is a valid date string (e.g. ISO 8601) or JSON date before casting","Use the nullable explicit operator (DateTime?)jsonDynamicValue, which returns null instead of throwing, and check for null","Call GetValue on the raw JToken/JsonValue with TryGetValue-style handling or DateTime.TryParse on the string first","Guard the wrapper itself for null before casting"],"exampleFix":"// before\nvar created = (DateTime)jsonDynamicValue[\"CreatedAt\"];\n// after\nvar created = (DateTime?)jsonDynamicValue[\"CreatedAt\"] ?? DateTime.UtcNow;","handlingStrategy":"type-guard","validationCode":"// pre-check before casting\nif (jsonDynamicValue is null) throw new InvalidOperationException(\"null wrapper\");\nvar raw = jsonDynamicValue.ToString();\nif (!DateTime.TryParse(raw, CultureInfo.InvariantCulture, DateTimeStyles.None, out _))\n    throw new InvalidOperationException($\"'{raw}' is not a DateTime\");\nvar dt = (DateTime)jsonDynamicValue;","typeGuard":"static bool TryGetDateTime(JsonDynamicValue v, out DateTime value)\n{\n    value = default;\n    if (v is null) return false;\n    var dt = (DateTime?)v;\n    if (dt is null) return false;\n    value = dt.Value;\n    return true;\n}","tryCatchPattern":"DateTime dt;\ntry\n{\n    dt = (DateTime)jsonDynamicValue[\"CreatedAt\"];\n}\ncatch (InvalidCastException ex)\n{\n    // log and fall back to a sentinel/default\n    dt = DateTime.MinValue;\n}","preventionTips":["Prefer the nullable casts ((DateTime?)) when absence is a valid state","Validate JSON shape against an expected schema before dynamic access","Store dates as ISO 8601 strings in JSON","Add unit tests covering null and wrong-type JSON fields"],"tags":["casting","invalidcastexception","json","datetime"],"backgroundTag":"type-mismatch","analyzedSha":"4306c0717fe573f6fca1b4955909ddab6a192807","analyzedAt":"2026-09-13T17:41:05.024Z","contentChangedAt":"2026-09-13T17:41:05.024Z","schemaVersion":2},"datasetVersion":"2026-09-15T23:17:13.987Z"}