{"record":{"id":"5965847ed0c42d30","repo":"JamesNK/Newtonsoft.Json","slug":"can-not-convert-0-to-datetime","errorCode":null,"errorMessage":"Can not convert {0} to DateTime.","messagePattern":"Can not convert (.+?) to DateTime\\.","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Src/Newtonsoft.Json/Linq/JToken.cs","lineNumber":671,"sourceCode":"            return Convert.ToInt64(v.Value, CultureInfo.InvariantCulture);\n        }\n\n        /// <summary>\n        /// Performs an explicit conversion from <see cref=\"JToken\"/> to <see cref=\"Nullable{T}\"/> of <see cref=\"DateTime\"/>.\n        /// </summary>\n        /// <param name=\"value\">The value.</param>\n        /// <returns>The result of the conversion.</returns>\n        public static explicit operator DateTime?(JToken? value)\n        {\n            if (value == null)\n            {\n                return null;\n            }\n\n            JValue? v = EnsureValue(value);\n            if (v == null || !ValidateToken(v, DateTimeTypes, true))\n            {\n                throw new ArgumentException(\"Can not convert {0} to DateTime.\".FormatWith(CultureInfo.InvariantCulture, GetType(value)));\n            }\n\n#if HAVE_DATE_TIME_OFFSET\n            if (v.Value is DateTimeOffset offset)\n            {\n                return offset.DateTime;\n            }\n#endif\n\n            return (v.Value != null) ? (DateTime?)Convert.ToDateTime(v.Value, CultureInfo.InvariantCulture) : null;\n        }\n\n#if HAVE_DATE_TIME_OFFSET\n        /// <summary>\n        /// Performs an explicit conversion from <see cref=\"JToken\"/> to <see cref=\"Nullable{T}\"/> of <see cref=\"DateTimeOffset\"/>.\n        /// </summary>\n        /// <param name=\"value\">The value.</param>\n        /// <returns>The result of the conversion.</returns>","sourceCodeStart":653,"sourceCodeEnd":689,"githubUrl":"https://github.com/JamesNK/Newtonsoft.Json/blob/4f73e74372445108d2c1bda37b36e6f5e43402e0/Src/Newtonsoft.Json/Linq/JToken.cs#L653-L689","documentation":"Thrown by the explicit nullable cast operator DateTime?(JToken?) at JToken.cs:671. With nullable:true, JSON null/undefined tokens pass and return null. The ArgumentException is raised only when the token is not a JValue (container) or its type is outside DateTimeTypes = {Date, String, Comment, Raw} — i.e. Integer, Float, Boolean, Guid, Uri, Bytes, Object, Array.","triggerScenarios":"Casting an Integer/Float/Boolean JValue to (DateTime?)token; casting a JObject/JArray or a Guid/Uri to DateTime?. A JSON null is accepted and returns null.","commonSituations":"An API returns dates as numeric ticks/epoch but code expects a Date or ISO string; a field that became a boolean flag is read as a date; a container where a scalar date was expected.","solutions":["Check token.Type is Date or String before casting.","If the value is an epoch/tick integer, convert explicitly (e.g. DateTimeOffset.FromUnixTimeSeconds((long)token).DateTime) rather than the DateTime cast.","Use token.Value<DateTime?>() which yields default for non-convertible tokens.","Deserialize into a typed POCO with a nullable DateTime property."],"exampleFix":"// before\nDateTime? dt = (DateTime?)token[\"created\"]; // throws when created is an epoch int\n\n// after\nDateTime? dt = token[\"created\"].Type == JTokenType.Integer\n    ? DateTimeOffset.FromUnixTimeSeconds((long)token[\"created\"]).LocalDateTime\n    : (DateTime?)token[\"created\"];","handlingStrategy":"type-guard","validationCode":"// Verify the token is a date-or-string scalar (nullable cast tolerates JSON null)\nstatic bool CanToNullableDateTime(JToken? t) =>\n    t is not JValue v || v.Type is JTokenType.Date or JTokenType.String\n        or JTokenType.Null or JTokenType.Undefined;","typeGuard":"static DateTime? SafeDateTime(JToken? t) => t switch {\n    JValue v when v.Type is JTokenType.Date or JTokenType.String => (DateTime?)t,\n    JValue v when v.Type is JTokenType.Null or JTokenType.Undefined => null,\n    _ => null // integer epoch, bool, container, etc.\n};","tryCatchPattern":"try\n{\n    DateTime? dt = (DateTime?)token;\n}\ncatch (ArgumentException ex) when (ex.Message.StartsWith(\"Can not convert\"))\n{\n    // token is numeric/bool/container; handle epoch or default\n}","preventionTips":["Convert epoch integers explicitly rather than using the DateTime cast.","Check token.Type is Date or String before casting.","Use token.Value<DateTime?>() for tolerant default handling.","Deserialize into a nullable DateTime POCO property."],"tags":["linq-to-json","jtoken","cast","nullable-datetime","argumentexception"],"analyzedSha":"4f73e74372445108d2c1bda37b36e6f5e43402e0","analyzedAt":"2026-08-07T06:10:08.596Z","schemaVersion":2},"datasetVersion":"2026-08-07T07:17:06.508Z"}