Add one year to date

38 visualizzazioni (ultimi 30 giorni)
Behrooz Daneshian
Behrooz Daneshian il 5 Gen 2023
Commentato: Steven Lord il 5 Gen 2023
Hi all,
Assume we have a date character='2022-01-05". What is the simplest way to add one year to that?

Risposta accettata

Bora Eryilmaz
Bora Eryilmaz il 5 Gen 2023
Modificato: Bora Eryilmaz il 5 Gen 2023
You can use the datetime and years commands to do what you want:
date = '2022-01-05';
d = datetime(date)
d = datetime
05-Jan-2022
d1 = d + years(1)
d1 = datetime
05-Jan-2023 05:49:12
string(d1)
ans = "05-Jan-2023 05:49:12"
  2 Commenti
Behrooz Daneshian
Behrooz Daneshian il 5 Gen 2023
Thank you for your answer.
Steven Lord
Steven Lord il 5 Gen 2023
In this case you probably want to use calyears (to add 1 calendar year) instead of years (which adds 365.2425 days.)
date = '2022-01-05';
d = datetime(date)
d = datetime
05-Jan-2022
d1 = d + years(1)
d1 = datetime
05-Jan-2023 05:49:12
d2 = d + calyears(1)
d2 = datetime
05-Jan-2023
daysPerYearDuration = days(years(1))
daysPerYearDuration = 365.2425

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Dates and Time in Help Center e File Exchange

Tag

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by