'Trying to compare todays date to given date from HTML
I'm trying to compare dates as i take input from user using date in html and send it to servlet to validate it or know if it's today's date this is my trial and it would only work with two digit months as it prints month as 5 not 05
String date = request.getParameter("birth");
Date d = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(d);
int year = calendar.get(Calendar.YEAR);
int month = calender.get(Calendar.MONTH);
month+=1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
String dat = (Integer.toString(year)+"-"+Integer.toString(month)+"-"+Integer.toString(day));
PrintWriter out = response.getWriter();
if(dat.equals(date))
out.println("Today");
}}
i feel like the code just looks so sad.
Solution 1:[1]
tl;dr
LocalDate
.parse(
"2022-05-24"
)
.isEqual(
LocalDate
.now(
ZoneId.of( "America/Edmonton" )
)
)
Avoid legacy classes
Do not use Calendar
, Date
, SimpleDateFormat
classes. These terrible classes were years ago supplanted by the modern java.time classes defined in JSR 310.
Compare objects, not text
Do not compare dates as text. Compare objects instead.
LocalDate
Parse your textual input into a LocalDate
if you are working with date-only, without time of day, and without time zone.
ISO 8601
Apparently your input string is in standard ISO 8601 format, YYYY-MM-DD. If so, no need to specify a formatting pattern.
String input = "2022-05-24" ;
LocalDate ld = LocalDate.parse( input ) ;
Capture the current date. Time zone is crucial here. For example, at the same simultaneous moment it can be tomorrow in Tokyo Japan while yesterday in Toledo Ohio US.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
LocalDate today = LocalDate.now( z ) ;
LocalDate#isEqual
Compare.
boolean isToday = ld.isEqual( today ) ;
All this has been covered many times already on Stack Overflow. Search to learn more.
Solution 2:[2]
you could just add zero when month is < 10 : for example:
if(month < 10)
String dat = (Integer.toString(year)+"-0"+Integer.toString(month)+"-"+Integer.toString(day));
else
String dat = (Integer.toString(year)+"-"+Integer.toString(month)+"-"+Integer.toString(day));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Bandar Alrooqi |