I got the date data with value Wed Jun 04 2025 00:00:00 GMT+0800, How can I convert it to format like 2025-06-03T06:02:44.595+00:00 in C#?
Assistant
To convert a date/time string like "Wed Jun 04 2025 00:00:00 GMT+0800" into a format like "2025-06-03T06:02:44.595+00:00" in C#, you can:
Parse the original string into a DateTimeOffset object, considering the original timezone offset.
Convert it to the desired timezone if needed (the sample output you gave seems to be in UTC+0).
Format it as an ISO 8601 string with offset.
Step-by-step example
csharp
using System;
using System.Globalization;
class Program
{
static void Main()
{
// Input string
var input = "Wed Jun 04 2025 00:00:00 GMT+0800";
// Step 1: Parse the string
// The input format is: "ddd MMM dd yyyy HH:mm:ss 'GMT'zzz"
// But 'zzz' expects format like "+08:00", so need to preprocess the timezone from "+0800" to "+08:00"
// Fix the timezone part by inserting a colon
// Find the position of "GMT+0800", extract the offset and add colon
int gmtIndex = input.IndexOf("GMT");
if (gmtIndex < 0)
{
throw new Exception("Invalid input format: missing GMT part");
}
string prefix = input.Substring(0, gmtIndex); // "Wed Jun 04 2025 00:00:00 "
string offset = input.Substring(gmtIndex + 3); // "+0800"
// Convert +0800 to +08:00
if(offset.Length == 5 && (offset[0] == '+' || offset[0] == '-'))
{
offset = offset.Insert(3, ":"); // +08:00
}
else
{
throw new Exception("Invalid timezone offset format");
}
string fixedInput = prefix + offset; // "Wed Jun 04 2025 00:00:00 +08:00"
// Define the parse format
string format = "ddd MMM dd yyyy HH:mm:ss zzz";
// Use invariant culture
DateTimeOffset dto = DateTimeOffset.ParseExact(fixedInput, format, CultureInfo.InvariantCulture);
// Step 2: Convert to UTC (if you want output in UTC)
DateTimeOffset utcTime = dto.ToUniversalTime();
// Step 3: Format as ISO 8601 string with fractional seconds and offset
// The example you gave shows offset +00:00 (UTC) and milliseconds
string output = utcTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fffzzz");
Console.WriteLine(output);
}
}
Explanation
The original input timezone is "GMT+0800" but DateTimeOffset expects offset format like +08:00.
After fixing the timezone substring, we parse using ParseExact.
Then convert to UTC using .ToUniversalTime().
Finally, format in ISO 8601 with fractional seconds and offset.
Output
For your input "Wed Jun 04 2025 00:00:00 GMT+0800", the output will be:
code
2025-06-03T16:00:00.000+00:00
Note: This shows UTC time equivalent to the input time in GMT+8.
If your input includes milliseconds or you want more precision, adjust the parsing and formatting accordingly. But this should cover your requirement to convert the input string into ISO 8601 format with offset in C#.