I have the following string which I'm trying to convert to a DateTime
object:
02-21-2022 23:40:29.039-60
I'm struggling with the offset as it's in minutes and now what the format specifier z
expects it to be (in hours)
How can I convert that to a DateTime
preserving the offset?
CodePudding user response:
Using Regex :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Text.RegularExpressions;
namespace ConsoleApplication17
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
string input = "02-21-2022 23:40:29.039-60";
string pattern = @"(?'date'.*)(?'timezone'[- ]\d )";
Match match = Regex.Match(input, pattern);
DateTime date =
DateTime.Parse(match.Groups["date"].Value "GMT");
int timezone = int.Parse(match.Groups["timezone"].Value) / 60;
date.AddHours(timezone);
}
}
}
CodePudding user response:
Either use a different format or split the string and parse each part separately. It would be better to not use such an unusual format. IS8601 would be a far better option.
On top of that, DateTime
has no offset. Parsing a string with an offset produces a UTC value
Timezone offsets are typically represented as time values. When integers are used, they represent hours, not minutes. 02
or UTC 2
means UTC plus two hours, not two minutes. The following statement works, but treats -6
as 6 hours :
var thatDate="02-21-2022 23:40:29.039-6";
var date=DateTime.ParseExact(thatDate,"MM-dd-yyyy HH:mm:ss.fffz",CultureInfo.InvariantCulture);
Console.WriteLine(date.ToString("u"));
This produces
2022-02-22 07:40:29Z
Type parsing functions can handle many custom formats but not every possible combination. Handling timezone offsets as minutes is both unusual and conflicts with an existing common format.
If you have to use that format, you'd have to write your own parser. One possibility would be to split the string in parts. This is easy if the string has a fixed length. In this case, the string can be split at the 24th character:
var thatDate="02-21-2022 23:40:29.039-60";
var datePart=thatDate[..23];
var offsetPart=thatDate[23..];
var date=DateTime.Parse(datePart,CultureInfo.InvariantCulture,DateTimeStyles.AssumeUniversal);
var offset=int.Parse(offsetPart);
var finalDate=date.AddMinutes(offset);
Console.WriteLine(finalDate.ToString("u"));
This prints
2022-02-22 00:40:29Z