Search code examples
c#datetimein-app-purchasedatetimeoffsetamazon-appstore

Parsing amazon app store purchaseDate receipt string to DateTime


The purchase receipt from the amazon app store has a purchase date formatted as "Wed Feb 02 17:28:08 GMT+00:00 2022" however I'm not sure how to properly convert this to a valid DateTime due to the timezone offset being included.

DateTime.Parse("Wed Feb 02 17:28:08 GMT+00:00 2022");

The standard DateTime.Parse function just throws FormatException: String was not recognized as a valid DateTime.

How can I parse this string as DateTime?

EDIT:
A commented suggested DateTimeOffset.Parse however this also gives the same FormatException

DateTimeOffset.Parse("Wed Feb 02 17:28:08 GMT+00:00 2022", CultureInfo.InvariantCulture);

Solution

  • You can try DateTimeOffset.ParseExact where you pass the expected format string. The correct format string for your date is "ddd MMM dd HH:mm:ss 'GMT'zzz yyyy":

    var date = DateTimeOffset.ParseExact(dateString, 
                           "ddd MMM dd HH:mm:ss 'GMT'zzz yyyy", 
                           CultureInfo.InvariantCulture);
    

    However, you'll still have issues if GMT doesn't appear in the string, but some other Timezome string does. You could try TryParseExact instead, and if it fails to parse then replace the Timezone characters in the string (assuming there will always be 3 characters GMT, CST, etc):

    if (DateTimeOffset.TryParseExact(dateString,  
                                    "ddd MMM dd HH:mm:ss 'GMT'zzz yyyy", 
                                    CultureInfo.InvariantCulture, 
                                    DateTimeStyles.None, 
                                    out var dt))
    {    
        // it worked
    }
    else 
    {
        // try to replace the Timezone string
        var replaced = dateString.Replace(dateString.Substring(20, 3), "");
        date = DateTimeOffset.ParseExact(replaced, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture))
    }
    

    To use ParseExact or TryParseExact you need to know the expected format string before parsing.