0

I'm working with an application that provides date times strings containing timezones. Here is an example:

21/07/2011 10:42 AM BST

When I parse this using DateTime.Parse, including specifying the British locale...

[TestMethod]
public void ParseDateStringWithBSTTimeZone()
{
    string dateString = "21/07/2011 10:42 AM BST";
    var date = DateTime.Parse(dateString, CultureInfo.CreateSpecificCulture("en-GB"));
    Assert.AreEqual(new DateTime(2011, 7, 21, 9, 42, 0), date);
}

I get the following error:

System.FormatException: The string was not recognized as a valid DateTime. There is an unknown word starting at index 20.

How can I parse this date time string? Doesn't .NET DateTime library support dates with this format?

Dan Stevens
  • 6,392
  • 10
  • 49
  • 68
  • This solution on this post used a String.Replace() to change the local to the hour offset. https://stackoverflow.com/questions/241789/parse-datetime-with-time-zone-of-form-pst-cest-utc-etc – AlwaysLearning Nov 01 '19 at 18:06
  • Locale and time zone are orthogonal. The locale tells me that you are using date formats in British English. It doesn't tell me you want to use British Summer Time. Perhaps I'm actually interested in Bangladesh Standard Time. (BST is not a unique identifier!) – Matt Johnson-Pint Nov 01 '19 at 18:15
  • 1
    Also note: the solution about replacing the zone with an offset doesn't support time changes (Standard, Daylight Savings), at least not as stated. You'll need to make sure you base the offset on the current date's UTC offset, not a constant like "+1". – Ed Gibbs Nov 01 '19 at 18:18

0 Answers0