date question

1 次查看(过去 30 天)
Leah
Leah 2011-2-17
how do i go 6 months back?
so today is Feb 17, 2010 I use datevec to transform to Feb 1,2011, I can just do datenum-6*30 and transform that to Aug 1,2010 but is there a better way to do this? I want to make the intra month assumption above and get the first of the month 6 months back from the first of whatever month I am in.
d1=datevec(date())
d1(3)=1
d2=datenum(d1)-6*30
d2=datevec(d2)
d2(3)=1
datestr(d2)
thanks for you help

采纳的回答

Walter Roberson
Walter Roberson 2011-2-17
d1 = datevec(date());
datestr([d1(1)-1 d1(2)+6 1 0 0 0])
This uses the trick that you cannot go negative on months, but you can go back a year and forward 6 months from there.
Do not use -6*30 as that does not take in to account the length of months and will not handle leap-years properly.
ps: today is Feb 17, 2011 not 2010 :)

更多回答(1 个)

Leah
Leah 2011-2-17
that's exactly why i didn't want to do it myway. The problem is you know in the example you are crossing a year, so that doesn't work. I want to be able to do this for every day.
bah! 2011, like how i fixed the second one ;)
  1 个评论
Walter Roberson
Walter Roberson 2011-2-17
I tested my code before posting; it works fine whether years are crossed or not.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Time Series Objects 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by