[Solved] Problem with adding days to the DateTime.

Started by Stupot, Thu 23/05/2013 03:08:20

Previous topic - Next topic

Stupot

For a puzzle in my game I am using 'Best Before' dates on crisp packets. The crisps have to still be in date by an arbitrary number of days. Let's say three days.
I thought it would be a cool touch to actually use the player's system date, so that if he is playing the game today (23/05/2013), the crisps in the game would have a best before date of 26/05/2013, three days from today.

This is simple enough, I have just added "+ 3" to the DayOfMonth label:

Code: AGS

function iCrisp_Look()
{
  cEgo.Say("Emtpy packet of Salt and Vinegar.");
  DateTime *dt = DateTime.Now;
  cEgo.Say("Best Before: %02d/%02d/%04d", dt.DayOfMonth + 3, dt.Month, dt.Year);
}


The problem lies in that if the player were to be playing the game on May 31st, the result would be a crisp packet with a Best Before date of 34/05/2013, rather than the desired 03/06/2013.

Is there a way to manipulate this so that adding days will affect the month (and the year, if you happened to be playing at the end of December) instead of just adding impossible numbers of days onto the current month?

Thanks :-)
MAGGIES 2024
Voting is over  |  Play the games

Khris

Sure:
Code: ags
  DateTime *dt = DateTime.Now;
  int days = 31, m = dt.Month;
  if (m == 2) days = 28;
  if (m == 4 || m == 6 || m == 9 || m == 11) days = 30;
  int day = dt.DayOfMonth;
  int year = dt.Year;

  day += 3;
  if (day > days) {
    day -= days;
    m++;
  }
  if (m == 13) {
    m = 1;
    year++;
  }
  cEgo.Say("Best Before: %02d/%02d/%04d", day, m, year);

Stupot

Beautiful. Works like a charm.  Thanks Khris :)
MAGGIES 2024
Voting is over  |  Play the games

SMF spam blocked by CleanTalk