I'm working on Hotel management application [desktop] and I noticed, the date changing time hotels system is not 00:00 am , it's between 1AM and 6AM so reservations and room status etc. should be stay until audit time.When the user make audit the new day will start.
That's why I need to create a method that stop date change at midnight and return new date when audit button clicked. Briefly I have to create central system for date.
As a result; when I use this date in all classes every methods will work synchronously[blockade, reservations, check in, check out etc.] but I couldn't find good way to do this.
I'm thinking around some code like this :
package com.coder.hms.utils;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class CustomDateFactory {
private Date date;
private Calendar calendar;
private SimpleDateFormat sdf;
public CustomDateFactory() {
//for formatting date as desired
sdf = new SimpleDateFormat("yyyy-MM-dd");
}
public void setValidDateUntilAudit(int counter) {
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
@Override
public void run() {
//get hour and minute from calendar
calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR);
int min = calendar.get(Calendar.MINUTE);
int sec = calendar.get(Calendar.SECOND);
//check if the field value equals -1
if (counter == -1) {
//and the time at 00:00
if (hour == 0 && min == 0 && sec == 2) {
//bring the date one day back
calendar.add(Calendar.DATE, counter);
date = calendar.getTime();
}
} else {
date = new Date();
}
}
};
timer.schedule(task, 0, 100);
}
public Date getDate() {
final String today = sdf.format(date);
final LocalDate ld = LocalDate.parse(today);
date = java.sql.Date.valueOf(ld);
return date;
}
}
After comments and helps I changed my code like this :
public class DateFactoryTest {
private LocalDate currentDate;
private LocalDateTime localDateTime;
public DateFactoryTest() {
currentDate = LocalDate.now();
localDateTime = LocalDateTime.now();
}
private void setTheDate(boolean isAuditted) {
if (localDateTime.getHour() <= 6 && isAuditted == false) {
currentDate.minusDays(1);
} else if (localDateTime.getHour() > 6 && isAuditted == true) {
ImageIcon icon = new ImageIcon(getClass().getResource("/com/coder/hms/icons/dialogPane_question.png"));
int choosedVal = JOptionPane.showOptionDialog(null, "You're doing early audit, are you sure about this?",
"Approving question", 0, JOptionPane.YES_NO_OPTION, icon, null, null);
if (choosedVal == JOptionPane.YES_OPTION) {
isAuditted = false;
}
}
}
private LocalDate getDate() {
return currentDate;
}
}
All answers, different ideas acceptable.