How can I make an algorithm that can give me the right values for year, month,day ,h,min,s?

2 次查看(过去 30 天)
I'm trying to make an algorithm that takes count if a year is a leap year and also to make it recognize the number of days of every month so that we have for example 31 december 2001 and the time is 23:59:00 and we add a minute we will obtain 1 jan 2002 00:00:00 . But the script seems to be faulty and the results aren't right.This is an algorithm for a function but I also want to put it in guide where a user could write the date using an editbox. The problem in this situation is what happens if a user puts as day 44 for example, The algorithm only takes account if the day is greater than 30, 31 ,28,29 and makes the day 1. Also another problem is if a user puts hour =0 , in my function I have that hour is 0 , day=day+1.THis condition was put because I have a tspan and the algorithm should work based the transformation of second in min,h,day.. Can somebody offer me some guidance over this problems that I'm trying to avoid? For the problem with the user input I was thinking of a notice message or something that won't let the user put a bigger value for that month.
t=3600;
year=2001;
anb=0; %leap year
%condition for leap year
if mod(year,4)~=0
anb=0;
else if mod(anb,100)~=0
anb=1;
else if mod(anb,400)~=0
anb=0;
else anb=1;
end
end
end
month= 12;
day=28;
hour=23;
min=25;
sec=17;
sec = sec + rem(t, 60);
min = rem(min + floor(t/60), 60);
hour = rem(hour + floor(t/3600), 24);
%conditions
if hour==0
day=day+1;
end
if (anb==1 && month==2 && day >29)
month=3;
day=1;
else if anb==0 && month==2 && day>28
month=3;
day=1;
end
end
if month==1||3||5||7||8||10 && day>31
month=month+1
day=1
else if month==4||6||9||11 && day>30
month=month+1
day=1
else if month==12 && day>31
year=year+1
month=1
day=1
end
end
end

采纳的回答

Steven Lord
Steven Lord 2018-2-26
If this is NOT a homework assignment and you're using release R2014b or later, just represent your date and time data using datetime. [If this IS a homework assignment, I'm guessing your professor wants you to implement the date and time handling yourself.]
  3 个评论
Steven Lord
Steven Lord 2018-2-26
编辑:Steven Lord 2018-2-26
BTW this doesn't do what you think it does.
if month==1||3||5||7||8||10 && day>31
If month is a scalar, this is equivalent to:
if day > 31
or
if (month==1) || 3 || 5 || 7 || 8 || 10 && day>31
The expression (anything) || 3 is true because 3 is nonzero. The expression true || 5 is true because both true and 5 are nonzero. Continuing that reasoning, it boils down to (true || 10) && (day > 31) or true && (day > 31).
If you want to check if a number is in a set of numbers, I recommend using the ismember or ismembertol functions.
[Edited to fix the missing or operators.]

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by