{"record":{"id":"e5b2887f1addf14b","repo":"JamesNK/Newtonsoft.Json","slug":"can-not-convert-0-to-datetimeoffset","errorCode":null,"errorMessage":"Can not convert {0} to DateTimeOffset.","messagePattern":"Can not convert (.+?) to DateTimeOffset\\.","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Src/Newtonsoft.Json/Linq/JToken.cs","lineNumber":588,"sourceCode":"                return Convert.ToBoolean((int)integer);\n            }\n#endif\n\n            return Convert.ToBoolean(v.Value, CultureInfo.InvariantCulture);\n        }\n\n#if HAVE_DATE_TIME_OFFSET\n        /// <summary>\n        /// Performs an explicit conversion from <see cref=\"Newtonsoft.Json.Linq.JToken\"/> to <see cref=\"System.DateTimeOffset\"/>.\n        /// </summary>\n        /// <param name=\"value\">The value.</param>\n        /// <returns>The result of the conversion.</returns>\n        public static explicit operator DateTimeOffset(JToken value)\n        {\n            JValue? v = EnsureValue(value);\n            if (v == null || !ValidateToken(v, DateTimeTypes, false))\n            {\n                throw new ArgumentException(\"Can not convert {0} to DateTimeOffset.\".FormatWith(CultureInfo.InvariantCulture, GetType(value)));\n            }\n\n            if (v.Value is DateTimeOffset offset)\n            {\n                return offset;\n            }\n\n            if (v.Value is string s)\n            {\n                return DateTimeOffset.Parse(s, CultureInfo.InvariantCulture);\n            }\n\n            return new DateTimeOffset(Convert.ToDateTime(v.Value, CultureInfo.InvariantCulture));\n        }\n#endif\n\n        /// <summary>\n        /// Performs an explicit conversion from <see cref=\"JToken\"/> to <see cref=\"Nullable{T}\"/> of <see cref=\"Boolean\"/>.","sourceCodeStart":570,"sourceCodeEnd":606,"githubUrl":"https://github.com/JamesNK/Newtonsoft.Json/blob/4f73e74372445108d2c1bda37b36e6f5e43402e0/Src/Newtonsoft.Json/Linq/JToken.cs#L570-L606","documentation":"Thrown by the explicit (non-nullable) cast operator DateTimeOffset(JToken) at JToken.cs:588. It validates the token type against DateTimeTypes = {Date, String, Comment, Raw}. Only date-carrying or string JValues are accepted; numbers, booleans, null, and containers are rejected with this ArgumentException. (A string value is later parsed via DateTimeOffset.Parse, so only the type gate, not parse failures, produces this specific message.)","triggerScenarios":"Casting a JSON null to (DateTimeOffset)token; casting an Integer (e.g. a unix epoch) or Float JValue to DateTimeOffset; casting a Boolean, Guid, Uri, or a JObject/JArray to DateTimeOffset.","commonSituations":"API returns a numeric epoch timestamp but code assumes an ISO-8601 string; field became null after a schema/version change; a date field represented as an object (e.g. {\"$date\": ...}) instead of a string.","solutions":["Use the nullable cast (DateTimeOffset?)token and null-coalesce, so a JSON null yields null rather than throwing.","If the value is a numeric epoch, convert manually: DateTimeOffset.FromUnixTimeSeconds((long)token) — but first cast via long, not DateTimeOffset.","Ensure the JSON value is an ISO-8601 string so its JTokenType is String (accepted by DateTimeTypes).","Check token.Type is Date or String before the non-nullable cast."],"exampleFix":"// before\nDateTimeOffset dto = (DateTimeOffset)token[\"ts\"]; // throws for numeric/null epoch\n\n// after\nDateTimeOffset dto = token[\"ts\"].Type == JTokenType.Integer\n    ? DateTimeOffset.FromUnixTimeSeconds((long)token[\"ts\"])\n    : (DateTimeOffset?)token[\"ts\"] ?? DateTimeOffset.MinValue;","handlingStrategy":"type-guard","validationCode":"// Verify the token is a date-or-string scalar before the non-nullable DateTimeOffset cast\nstatic bool CanToDateTimeOffset(JToken? t) =>\n    t is JValue v && (v.Type == JTokenType.Date || v.Type == JTokenType.String);","typeGuard":"static DateTimeOffset? SafeDateTimeOffset(JToken? t) => t switch {\n    JValue v when v.Type is JTokenType.Date or JTokenType.String => (DateTimeOffset?)t,\n    JValue v when v.Type is JTokenType.Null or JTokenType.Undefined => null,\n    _ => null\n};","tryCatchPattern":"try\n{\n    DateTimeOffset dto = (DateTimeOffset)token;\n}\ncatch (ArgumentException ex) when (ex.Message.StartsWith(\"Can not convert\"))\n{\n    // token is numeric/null/object; handle epoch conversion or default\n}","preventionTips":["Use (DateTimeOffset?)token for fields that may be JSON null.","Confirm the JSON value is an ISO-8601 string or Date, not a numeric epoch.","Convert epoch integers explicitly via DateTimeOffset.FromUnixTimeSeconds rather than the DateTimeOffset cast.","Check token.Type is Date or String before the non-nullable cast."],"tags":["linq-to-json","jtoken","cast","datetimeoffset","argumentexception"],"analyzedSha":"4f73e74372445108d2c1bda37b36e6f5e43402e0","analyzedAt":"2026-08-07T06:10:08.596Z","schemaVersion":2},"datasetVersion":"2026-08-07T07:17:06.508Z"}