0

Tried:

select concat(cast(201201 as string), '01');

Returns 20120101

However:

select to_date(concat(cast(201201 as string), '01'));

Returns null.

How can I tell hive to treat the result of concat(cast(201201 as string), '01'); as a date, e.g. select date_add(to_date(concat(cast(201201 as string), '01')), -365);

1

I think you can do this with chained conversions . . . string to unix timestamp to timestamp to date:

select to_date(from_unixtime(unix_timestamp(concat(cast(201201 as string), '01'), 'YYYYMMDD')));
0

The ‘CAST’ operator allows converting between compatible types. But the value needs to be acceptable as input to create a value of the target type.

So, I expect that a string is acceptable for cast to a DATE value, only if that string represents a date the same way it'd be for creating a literal DATE instance. Try standard ISO 8601 representation:

SELECT
    CAST(concat('2012-01', '-01') AS DATE) AS dolor_date

If the string value is in a different format, you may need to use other string manipulation functions to get the correct format:

SELECT
    CAST(
        concat(
            substring(lorem_string, 1, 4),
            '-',
            substring(lorem_string, 5, 2),
            '-',
            substring(lorem_string, 7, 2) )
        AS DATE) AS dolor_date
  • Thanks for the answer. Actually, Within my larger query I'll be selecting a field of the format YYYYMM e.g. 201201 so not sure how to add in the dash '-' or even make the first component of concat a string? – Doug Fir Mar 12 at 1:27
  • SQL usually allows cast without the dashes - 20120101 should cast to date OK. Hive may be different, but it is worth trying. – DancingFool Mar 12 at 1:29
  • Tried select cast(concat(201201, '01') as date); but got Null. Thanks all the same – Doug Fir Mar 12 at 1:32

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.