Лайфхак: как хранить свою еду в общественном холодильнике

Если вдруг в общественном холодильнике надо помечать свою еду именем и сроком годности, то я могу предложить наилучшее решение:
Пишете имя и слово «СЕГОДНЯ«.

И вуаля, хак сработал.

Приходит, значит, человек управляющий холодильником и проверяет еду по следующему алгоритму

Calendar c = Calendar.getInstance();

// set the calendar to start of today
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);

// and get that as a Date
Date today = c.getTime();

// or as a timestamp in milliseconds
long todayInMillis = c.getTimeInMillis();

Fridge fridge = context.getCurrentFridge(); //new Fridge(); as noted by experienced users - no need to create new fridge on every validation.
for (Food food: fridge.getFoodList())
{
// user-specified date which you are testing
// let's say the components come from a form or something
int year = food.getYear();
int month = food.getMonth();
int dayOfMonth = food.getDay();

// reuse the calendar to set user specified date
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);

// and get that as a Date
Date dateSpecified = c.getTime();

// test your condition
if (dateSpecified.before(today)) {
  throw new FoodExpiredException();
} 
}

А на моей еде всегда срок стоит СЕГОДНЯ, значит dateSpecified будет всегда больше, чем today.

Опять же внимательные пользователи протестировав код обнаружили проблему с вводом даты.
Чтобы избежать возможных проблем с форматом даты, стоит использовать следующую операцию на стикере:

DateFormat dateFormat = new SimpleDateFormat("dd MM, yyyy");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));

Leave a Reply

%d bloggers like this: