Question

I am trying to obtain the UTC time from a zoned datetime using LocalDateTime pattern in NodaTime using 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.

Was it helpful?

Solution

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"

Yes, because you've specified that you'll give it a two-digit hour, and you've only given one digit. Note that if you're using an AM/PM designator, you probably want h rather than H anyway.

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"

Yes, because you've specified that you want - as the separator, but you're using / in the text.

I suspect you want:

dateTimePattern = "M/dd/yyyy h:mm:ss tt";

Note that this has nothing to do with converting to UTC - it's just the parsing to LocalDateTime that's causing you problems.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top