Loading...
Logo
Processing Forum

Counting days

in Programming Questions  •  2 years ago  
I was wondering how could I write a simple application that counts the number of days from a certain date. I just want to be reminded how long ago I have stopped smoking:) However the day() and month() functions can tell the date, I'm not sure how to count days from a past event. Any ideas?

Replies(4)

Re: Counting days

2 years ago
Counting days is a real trick. You'd have to calculate the difference the difference between two dates in YYYY/MM/DD format, which involves knowing how many days are in each month, and which years are leap years. You certainly could work it out this way, but since this is just a simple program for your own use, why not just do:

int stopDay = 8;
int stopMonth = 6;
int stopYear = 2011;

println( "You have been smoke-free for " + 
String.valueOf(year()-stopYear) + " year(s), " + 
String.valueOf(month()-stopMonth) + " month(s), and " + 
String.valueOf(day()-stopDay) + " day(s). Good job!" );

Re: Counting days

2 years ago
I just counted the days since I stopped (58 days) and stored it in a variable. Then created two integers to store day() returns and see if there's any difference (midnight). When it changes, we add 1 to the days. Here's the code:

int start = 58;//9 june
PFont fontA;
String dasyleft;

void setup(){
  size(550,150);
  fontA=loadFont("Verdana-Bold-48.vlw");
  textFont(fontA, 32);
}
void draw(){
  background(7,33,88);
  int d1=day();
  delay(1000);
  int d2=day();
  if(d1 != d2){
    start+=1;
  }
 String daysleft=start+"days without cigarettes";
 textAlign(LEFT);
  text(daysleft, 50, 50);
}
 

Wonder if it will change after midnight!

Re: Counting days

2 years ago
Great! Thanks! The final code is:

Date OldDate = new Date("04/12/2011"); // M/D/Y
Date TodaysDate = new Date();
long mills_per_day = 1000 * 60 * 60 * 24;
long day_diff = ( TodaysDate.getTime() - OldDate.getTime() ) / mills_per_day;
print(day_diff);