views:

713

answers:

3

I'm trying to convert a VARIANT from VT_DATE to an invariant VT_BSTR. The following code works on Windows XP:

VARIANT va;
::VariantInit(&va);

// set the variant to VT_DATE
SYSTEMTIME st;
memset(&st, 0, sizeof(SYSTEMTIME));
st.wYear = 2008;
st.wMonth = 9;
st.wDay = 22;
st.wHour = 12;
st.wMinute = 30;

DATE date;
SystemTimeToVariantTime(&st, &date);

va.vt = VT_DATE;
va.date = date;

// change to a string
err = ::VariantChangeTypeEx(&va, 
       &va, 
       LOCALE_INVARIANT, 
       0, 
       VT_BSTR);

But on PPC 2003 and Windows Mobile 5, the above code returns E_FAIL. Can someone correct the above code or provide an alternative?

EDIT: After converting the date to a string, I'm using the string to do a SQL update. I want the update to work regardless of the device's regional settings, so that's why I'm trying to convert it to an "invariant" format.

I'm now using the following to convert the date to a format that appears to work:

err = ::VariantTimeToSystemTime(va.date, &time);
if (FAILED(err))
    goto cleanup;

err = strDate.PrintF(_T("%04d-%02d-%02d %02d:%02d:%02d.%03d"),
    time.wYear,
    time.wMonth,
    time.wDay,
    time.wHour,
    time.wMinute,
    time.wSecond,
    time.wMilliseconds);
+1  A: 

This isn't really an answer, but changing a date to a string isn't a Locale-invariant task - it highly depends on the locale. In this case, I'd convert the Variant Time to System Time, then use a sprintf-style function to convert it to a string

Paul Betts
A: 

Not certain in your context here, but it seems maybe you're on the wrong path. Why not use VarBstrFromDate? This aloows using a locale (or optionally ignoring one) and is probably far closer to what you want.

ctacke
VarBstrFromDate fails just like VariantChangeTypeEx when using LOCALE_INVARIANT (0x007f)
Chris Karcher
+1  A: 

(I'm sorry it's taken me a while to respond ('work', you know...))

I don't see anything wrong with the code, from the COM point of view.

Maybe the problem is with LOCALE_INVARIANT. It was introduced with Windows XP; maybe it's not supported in the Windows CE family?

Try changing the locale to LOCALE_USER_DEFAULT and check to see if you still get an error. Most of the time this would be the most appropriate locale anyway; especially if you are trying to display the value to the user.

If you truly need a specific format because you need to pass the value somewhere else that will parse it, try using a specific locale that matches your requirements; perhaps en_US.

Please let us know how it goes.

Euro Micelli
Unfortunately, converting to the user's locale is exactly what I'm trying _not_ to do. See the edit in the original post.I'm using similar code for converting a floating point number to its string representation, in which case LOCALE_INVARIANT _does_ work.
Chris Karcher