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

Returns 20120101


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);


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')));

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:

    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:

            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 agree to our terms of service, privacy policy and cookie policy

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