Lee Dat
Lee Dat

Reputation: 165

Date addition in odoo 10.0

I have a class :

class DateAddition(models.Model):
      _name = "studentmanagement.dateaddition"

      input_date = fields.Date()
      output_date = fields.Date()
      no_months = fields.Integer()

Then if I fill input_date = "26 Feb 2017" and no_months = 2, output_date would be "26 April 2017". How can I do it in odoo-10.0 by on_change ?

Upvotes: 1

Views: 315

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49774

I do not know how to hook this to your odoo on_change, but here is a routine to add or subtract months from your date string:

Code:

import datetime as dt

def add_month(date, months):
    assert isinstance(date, dt.date)
    year, month, day = date.year, date.month, date.day
    year += int((month + months-1) / 12)
    month = (month + months - 1) % 12 + 1
    return dt.date(year, month, day)

def add_month_from_string(date_string, months):
    date = dt.datetime.strptime(date_string, '%d %b %Y')
    return add_month(date, months).strftime('%d %b %Y')

Test Data:

test_data = (
    ("26 Feb 2017", 2, "26 Apr 2017"),
    ("6 Dec 2016", 3, "6 Mar 2017"),
    ("26 Feb 2017", -2, "26 Dec 2016"),
)

for have, inc, want in test_data:
    print(have, inc, add_month_from_string(have, inc), want)

Results:

('26 Feb 2017', 2, '26 Apr 2017', '26 Apr 2017')
('6 Dec 2016', 3, '06 Mar 2017', '6 Mar 2017')
('26 Feb 2017', -2, '26 Dec 2016', '26 Dec 2016')

Upvotes: 1

Related Questions