5

I have a string, which contains a date field. eg: "19-Jan-20"

I have created a new field, which I want to store the year value, as an integer.

In the field calculator, I have used

year(to_date("field_name", 'dd-MMM-yy'))

This works great, except that the year that comes out, is '1920', not '2020' The issue appears to be with the 'to_date' function.

My solution was to simply add 100 to the end, so it become

year(to_date("field_name", 'dd-MMM-yy')) + 100

This worked, but im just wondering if there i a more elegant solution or a setting to change somewhere. 'Default century' or something similar which would make this function work correctly.

3
  • 2
    I dont think it isnt elegant. But you could create a case when. Something like case when abs(year(now())-year(to_date("field_name", 'dd-MMM-yy'))) > 50 then year(to_date("field_name", 'dd-MMM-yy')) + 100
    – BERA
    Dec 2 '21 at 7:12
  • 5
    The QGIS function github.com/qgis/QGIS/blob/master/resources/function_help/json/… is using Qt function doc.qt.io/qt-5/qdate.html#fromString-2 . I believe that the function works correctly as it has been programmed in the 20th century and that the +100 is the best temporary solution until your data provider changes the year format to yyyy.
    – user30184
    Dec 2 '21 at 8:47
  • great thanks for confirming that. Who would have thought - QGIS having a Y2K bug. :p
    – nr_aus
    Dec 3 '21 at 1:32
2

Extract the year in two-digit format using right ([expression], 2) and add 2000:

right ("field_name",2)+2000

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.