Set the date and time manually
i'm trying to allow a customer to set the date and time they would want to make a reservation. The code which i have already completed creates lots of text in the text file when saved and crashes when you try to load it again.
This is my code for adding a reservation:
public static List<Reservation> addReservations(List<Reservation> reservations, List<Customer> customers) {
int newReservationId = Reservation.getNumberOfReservations() + 1;
String startString = readString("Enter Reservation date");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = null;
try {
date = sdf.parse(startString);
} catch (ParseException ex) {
Logger.getLogger(ProjectIncrement5.class.getName()).log(Level.SEVERE, null, ex);
}
Calendar dateTime = Calendar.getInstance();
dateTime.setTime(date);
listCustomers(customers, reservations);
int reservationCustomerId = readInt("Enter Customer Id", Customer.getNumberOfCustomers(), 1);
Customer reservationCustomer = customers.get(reservationCustomerId - 1);
Reservation res = new Reservation(newReservationId, dateTime, reservationCustomer);
reservations.add(res);
return reservations;
}
Reservation Class:
public class Reservation {
private int reservationId;
private Calendar dateTime;
private Customer customer;
private static int numberOfReservations = 0;
public Reservation() {
this.reservationId = 0;
this.dateTime = null;
this.customer = null;
numberOfReservations++;
}
public Reservation(int reservationId, Calendar dateTime, Customer customer) {
this.reservationId = reservationId;
this.dateTime = dateTime;
this.customer = customer;
numberOfReservations++;
}
public static int getNumberOfReservations() {
return numberOfReservations;
}
public int getReservationId() {
return reservationId;
}
public void setreservationId(int reservationId) {
this.reservationId = reservationId;
}
public Calendar getDateTime() {
return dateTime;
}
public Customer getCustomer()
{
return customer;
}
public void setCustomer(Customer customer)
{
this.customer = customer;
}
public String setDateTime() {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateString = formatter.format(this.dateTime.getTime());
return dateString;
}
@Override
public String toString() {
return "Reservation id: " + getReservationId() + ", "
+ "Date/Time " + setDateTime() +
"customer: " + getCustomer();
}
}
This is what saves into the text file causing the error:
1:java.util.GregorianCalendar[time=851385600000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/London",offset=0,dstSavings=3600000,useDaylight=true,transitions=242,lastRule=java.util.SimpleTimeZone[id=Europe/London,offset=0,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=1996,MONTH=11,WEEK_OF_YEAR=52,WEEK_OF_MONTH=4,DAY_OF_MONTH=24,DAY_OF_YEAR=359,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=4,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]:4:<
I think the error occurs when getting the instance of the calendar but I'm am unsure of how to do it an easier way and fix this problem. Can anyone help?
The problem is you store the Calendar.toString()
and not the real date into the text file.
Look at what you have posted:
firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1, YEAR=1996
, MONTH=11
,WEEK_OF_YEAR=52,WEEK_OF_MONTH=4, DAY_OF_MONTH=24
,DAY_OF_YEAR=359,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=4,AM_PM=0, HOUR=0
,HOUR_OF_DAY=0, MINUTE=0
, SECOND=0
,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]
That seems a correct date. I will say more, this seems a really complete date, with a lot of information doesn't??? ;)
I don't know how this date is supposed to be stored, but, for example, if you want to store date in format dd/MM/yyyy
use this lines of code to check if it's a valid date (you already do this in your code).
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
date = sdf.parse(startString);
After checking this, if the startString
is valid, you don't need to create any Calendar
instance just write startString
to the text file .
UPDATE:
So in my Reservation
class, instead of having: private Calendar dateTime
I will take that out and just have: private String startString
?
NOPE. The idea is:
Object
( Calendar
is ok, but Date will be also) String
. Sorry but I can't be more specific, I can't execute your code because a lot of parts are missing ( Customer
, readInt
, listCustomers
etc...).
I accept Jordi Castilla's Answer, and also want to tell other option to do the same. here you are saving the Date & Time to file using Calendar.toString()
method, instead you could use following code
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String stringToFile = df.format(date);//you can send this string to the file which you want to store the Date & Time
Avoid legacy date-time classes
The modern approach uses java.time classes. Avoid the troublesome, confusing, and poorly-designed old legacy date-time classes such as Calendar
.
LocalDate
Collect the date portion. Catch any DateTimeParseException
in case of bad input.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
try {
LocalDate ld = LocalDate.parse( input , f ) ;
} catch ( DateTimeParseException e ) {
…
}
Seems like you are not explicitly tracking the time-of-day. So the LocalDate
class suffices.
ISO 8601
When you serialize your data to a text file, you should be using standard ISO 8601 formats. These formats are designed to be practical & unambiguous, easy to parse by machine, easy to read by humans across cultures, and not assume proficiency in English.
The java.time classes use the standard formats by default when parsing and generating strings. Merely call toString
to generate.
String output = ld.toString() ; // Ex: 2017-01-23
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
上一篇: SimpleDateFormat年份和时区格式有问题吗?
下一篇: 手动设置日期和时间