Question

What is the name of this DateTime format:

Tue Apr 01 2014 00:00:00 GMT+0100 (GMT Daylight Time)

Is there anyway I could detect this format in code?

The reason I am asking is that I have a function with DateTime parameter, which comes in different formats, and I would like to detect the format type or name; so that I could convert them accorddingly to the simple format of dd/MM/yyyy hh:mm:ss.

The other second format I am getting is this: 2014-03-31T23:00:00.000Z.

Many thanks.

Edit

I wrote this function to convert from Tue Apr 01 2014 00:00:00 GMT+0100 (GMT Daylight Time) to dd/MM/yyyy hh:mm:ss. This function fails when the input is of type 2014-03-31T23:00:00.000Z.

I wonder how could possibly identify the type of parameter coming and convert accordingly?

public static DateTime ConvertDateObjectToDateTime(string dateToConvert)
{
    var value = new DateTime();
    if (!string.IsNullOrEmpty(dateToConvert))
    {
        int gmtIndex = dateToConvert.IndexOf("G", System.StringComparison.Ordinal);

        string newDate = dateToConvert.Substring(0, gmtIndex).Trim();

        value = DateTime.ParseExact(newDate, "ddd MMM dd yyyy HH:mm:ss", CultureInfo.InvariantCulture);
        return value;
    }
    return value;
}
Was it helpful?

Solution

The second is definitely UTC, however, the first could be UTC + offset or it could be Local + offset (it looks like the latter the more I examine it). The best tool you have in your armoury for parsing specific dates is the ParseExact method.


Based on your edit, I am concerned about the fact you are ignoring the timezone information. You are assuming at this point that the date is already UTC (which it may not be) and just parsing/treating it as is...

However, to answer your particular question

I wonder how could possibly identify the type of parameter coming and convert accordingly?

You don't actually need to do that, ParseExact has an overload which allows you to specify multiple formats

value = DateTime.ParseExact(newDate, 
    new[] { "ddd MMM dd yyyy HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss.fff'Z'" }, 
    CultureInfo.InvariantCulture, 
    DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top