Tuesday, May 28, 2013

Zoned dateTime to UTC Time - LocalDateTimePattern throws exception

Zoned dateTime to UTC Time - LocalDateTimePattern throws exception

I am trying to obtain the UTC time from a zoned datetime using LocalDateTime pattern in NodaTime suing the below code.
public string getUtcTimeFromZonedTime(string dateTimeString, string timeZoneID,
                                      string dateTimePattern, bool isDateTime)
{

    if (string.IsNullOrEmpty(dateTimePattern))
    {
        if (isDateTime)
        {
            dateTimePattern = "M/dd/yyyy HH:mm:ss tt";
        }
        else
        {
            dateTimePattern = "M/dd/yyyy";
        }
    }

    var pattern = LocalDateTimePattern.CreateWithInvariantCulture(dateTimePattern);

    var parseResult = pattern.Parse(dateTimeString);
    if (!parseResult.Success)
    {
        // throw an exception or whatever you want to do
    }

    var localDateTime = parseResult.Value;

    var timeZone = DateTimeZoneProviders.Tzdb[timeZoneID];

    // TODO: Consider how you want to handle ambiguous or "skipped" local date/time
    // values. For example, you might want InZoneStrictly, or provide your own custom
    // handler to InZone.
    var zonedDateTime = localDateTime.InZoneLeniently(timeZone);

    return zonedDateTime.ToDateTimeUtc().ToString();
}
I get an exception during Parsing during below mentioned scenarios- 1) If pattern is like "MM/dd/yyyy HH:mm:ss tt" and the DateTime string is something like "5/28/2013 1:02:ss PM" 2) If pattern is like "MM-dd-yyyy HH:mm:ss tt" and the DateTime string is something like "5/28/2013 1:02:ss PM"
For the first case, it will work if I change my pattern to "M/dd/yyyy HH:mm:ss tt", but i will end up losing the leading zero. Second case will work if I change the pattern to "MM/dd/yyyy HH:mm:ss tt"
Is there any alternative way for getting the UTC values or am I doing something wrong over here.