Trying to compare todays date to given date from HTML - java

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.

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.

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));

Related

how to iterate all days in last 30 days using Arraylist in java

I need to get all days between today date to past 30 date. and i want to set this days to arraylist .
I get past 30 days using Calendar in java now I want to get all dates and set them to the ArrayList
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date toDate = cal.getTime();
cal.add(Calendar.DATE, -30);
Date fromDate = cal.getTime();
help me for that
tl;dr
today.minusDays( 30 ).datesUntil( today ).toList()
Avoid legacy date-time classes
The Calendar class is not a fit for date-only values.
Furthermore that class is terribly flawed in design, and is now obsolete having been supplanted years ago by the modern java.time classes defined in JSR 310.
java.time.LocalDate
For date-only values, use LocalDate. To get a series of dates, call LocalDate.html#datesUntil to get a stream.
Get today’s date.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
LocalDate today = LocalDate.now( z ) ;
Go back 30 days.
LocalDate thirtyDaysAgo = today.minusDays( 30 ) ;
Get a Stream of dates.
Stream< LocalDate > datesStream = thirtyDaysAgo.datesUntil( today ) ;
Make a List of the objects from that stream.
List< LocalDate > dates = datesStream.toList() ;
We could combine those lines.
List< LocalDate > dates = today.minusDays( 30 ).datesUntil( today ).toList() ;

Java - Date format for Multiple Scenarios

I have a java component to format the date that I retrieve. Here is my code:
Format formatter = new SimpleDateFormat("yyyyMMdd");
String s = "2019-04-23 06:57:00.0";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss.S");
try
{
Date date = simpleDateFormat.parse(s);
System.out.println("Formatter: "+formatter.format(date));
}
catch (ParseException ex)
{
System.out.println("Exception "+ex);
}
The code works great as long as the String s has the format "2019-04-23 06:57:00.0";
My Question is, how to tweak this code so it will work for below scenarios ex,
my s string may have values like
String s = "2019-04-23 06:57:00.0";
or
String s = "2019-04-23 06:57:00";
Or
String s = "2019-04-23";
right now it fails if I don't pass the ms.. Thanks!
Different types
String s = "2019-04-23 06:57:00";
String s = "2019-04-23";
These are two different kinds of information. One is a date with time-of-day, the other is simply a date. So you should be parsing each as different types of objects.
LocalDateTime.parse
To comply with the ISO 8601 standard format used by default in the LocalDateTime class, replace the SPACE in the middle with a T. I suggest you educate the publisher of your data about using only ISO 8601 formats when exchanging date-time values as text.
LocalDateTime ldt1 = LocalDateTime.parse( "2019-04-23 06:57:00".replace( " " , "T" ) ) ;
The fractional second parses by default as well.
LocalDateTime ldt2 = LocalDateTime.parse( "2019-04-23 06:57:00.0".replace( " " , "T" ) ) ;
See this code run live at IdeOne.com.
ldt1.toString(): 2019-04-23T06:57
ldt2.toString(): 2019-04-23T06:57
LocalDate.parse
Your date-only input already complies with ISO 8601.
LocalDate ld = LocalDate.parse( "2019-04-23" ) ;
See this code run live at IdeOne.com.
ld.toString(): 2019-04-23
Date with time-of-day
You can strip out the time-of-day from the date.
LocalDate ld = ldt.toLocalDate() ;
And you can add it back in.
LocalTime lt = LocalTime.parse( "06:57:00" ) ;
LocalDateTime ldt = ld.with( lt ) ;
Moment
However, be aware that a LocalDateTime does not represent a moment, is not a point on the timeline. Lacking the context of a time zone or offset-from-UTC, a LocalDateTime cannot hold a moment, as explained in its class JavaDoc.
For a moment, use the ZonedDateTime, OffsetDateTime, or Instant classes. Teach the publisher of your data to include the offset, preferably in UTC.
Avoid legacy date-time classes
The old classes SimpleDateFormat, Date, and Calendar are terrible, riddled with poor design choices, written by people not skilled in date-time handling. These were supplanted years ago by the modern java.time classes defined in JSR 310.
In case of you have optional parts in pattern you can use [ and ].
For example
public static Instant toInstant(final String timeStr){
final DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH[:mm[:ss[ SSSSSSSS]]]")
.withZone(ZoneId.of("UTC"));
try {
return Instant.from(formatter.parse(timeStr));
}catch (DateTimeException e){
final DateTimeFormatter formatter2 = DateTimeFormatter
.ofPattern("yyyy-MM-dd")
.withZone(ZoneId.of("UTC"));
return LocalDate.parse(timeStr, formatter2).atStartOfDay().atZone(ZoneId.of("UTC")).toInstant();
}
}
cover
yyyy-MM-dd
yyyy-MM-dd HH
yyyy-MM-dd HH:mm
yyyy-MM-dd HH:mm:ss
yyyy-MM-dd HH:mm:ss SSSSSSSS

How to add current timestamp to Date object in Java?

I need to pass in a Date object into a service which my API is calling. I have the info on the day, month, and year for the Date but also need a timestamp. The service is expecting it in this format:
<date>2015-04-01T00:00:00-05:00</date>
How can I add something to the Date to get this format?
Never use java.util.Date. Supplanted by java.time.Instant.
Get your date portion.
LocalDate ld = LocalDate.of( 2015 , 4 , 1 ) ;
Or use the readable Month enum.
LocalDate ld = LocalDate.of( 2015 , Month.APRIL , 1 ) ;
Get the time of day when the day starts in some particular time zone. Do not assume the day starts at 00:00:00, may be some other time such as 01:00:00. Let java.time figure that out for you.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
Generate a string in your desired format, a standard ISO 8601 format.
DateTimeFormatter f = DateTimeFormatter.ISO_OFFSET_DATE_TIME ;
String output = zdt.format( f ) ;
To see that moment in UTC, extract a Instant.
Instant instant = zdt.toInstant() ;
Conversion
If you must inter-operate with old code not yet updated for java.time, you can call new conversion methods added to the old classes. These include Date::from( Instant ).
java.util.Date d = java.util.Date.from( instant ) ;
Going the other direction.
Instant instant = d.toInstant() ;
Get back to a time zone other than UTC.
ZonedDateTime zdt = instant.atZone( ZoneId.of( "Pacific/Auckland" ) ) ; // Same moment, different wall-clock time.
Working with dates in Java is an ugly mess, always has been. Date class is mostly deprecated now. I am using LocalDateTime where you can construct it by calling year, month, day, hour, minute, and seconds. Here is what I could come up with:
LocalDateTime ldt = LocalDateTime.of(1997, Month.SEPTEMBER, 2, 1, 23, 0);
ZonedDateTime systemTime = ldt.atZone(ZoneId.systemDefault());
DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; //Basil's idea
System.out.println(systemTime.format(formatter));
Output:
1997-09-02T01:23:00-05:00
You could use SimpleDateFormat for this.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
dateFormat.format(new Date());

Plus 1 hour and 1 day in date using java 8 apis

I have this code to add 1 hour or 1 day in date Java 8, but doesn´t work
String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(DATE_FORMAT);
Date parse = format.parse("2017-01-01 13:00:00");
LocalDateTime ldt = LocalDateTime.ofInstant(parse.toInstant(), ZoneId.systemDefault());
ldt.plusHours(1);
ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
Date te = Date.from(zdt.toInstant());
What´s wrong? The code shows: Sun Jan 01 13:00:00 BRST 2017
LocalDateTime is immutable and returns a new LocalDateTime when you call methods on it.
So you must call
ldt = ldt.plusHours(1);
Apart from the issue that you don't use the result of your date manipulation (ldt = ldt.plusHours(1)), you don't really need to go via a LocalDateTime for this operation.
I would simply use an OffsetDateTime since you don't care about time zones:
OffsetDateTime odt = parse.toInstant().atOffset(ZoneOffset.UTC);
odt = odt.plusDays(1).plusHours(1);
Date te = Date.from(odt.toInstant());
You could even stick to using Instants:
Instant input = parse.toInstant();
Date te = Date.from(input.plus(1, DAYS).plus(1, HOURS));
(with an import static java.time.temporal.ChronoUnit.*;)
tl;dr
LocalDateTime.parse( // Parse input string that lacks any indication of offset-from-UTC or time zone.
"2017-01-01 13:00:00".replace( " " , "T" ) // Convert to ISO 8601 standard format.
).atZone( // Assign a time zone to render a meaningful ZonedDateTime object, an actual point on the timeline.
ZoneId.systemDefault() // The Question uses default time zone. Beware that default can change at any moment during runtime. Better to specify an expected/desired time zone generally.
).plus(
Duration.ofDays( 1L ).plusHours( 1L ) // Add a span of time.
)
Details
Do not mix the troublesome old legacy classes Date and Calendar with the modern java.time classes. Use only java.time, avoiding the legacy classes.
The java.time classes use the ISO 8601 standard formats by default when parsing and generating strings. Convert your input string by replacing the SPACE in the middle with a T.
String input = "2017-01-01 13:00:00".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
ALocalDateTime does not represent an actual moment, not a point on the timeline. It has no real meaning until you assign a time zone.
ZoneId z = ZoneId.systemDefault() ; // I recommend specifying the desired/expected zone rather than relying on current default.
ZonedDateTime zdt = ldt.atZone( z ) ;
A Duration represents a span of time not attached to the timeline.
Duration d = Duration.ofDays( 1L ).plusHours( 1L ) ;
ZonedDateTime zdtLater = zdt.plus( d ) ;

extract day from Date

I receive a timestamp from a SOAP service in milliseconds. So I do this:
Date date = new Date( mar.getEventDate() );
How can I extract the day of the month from date, since methods such as Date::getDay() are deprecated?
I am using a small hack, but I do not think this is the proper way to obtain day-of-month.
SimpleDateFormat sdf = new SimpleDateFormat( "dd" );
int day = Integer.parseInt( sdf.format( date ) );
Use Calendar for this:
Calendar cal = Calendar.getInstance();
cal.setTime(mar.getEventDate());
int day = cal.get(Calendar.DAY_OF_MONTH);
Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.
See the correct Answer by Ortomala Lokni, using the modern java.time classes. I am leaving this outmoded Answer intact as history.
The Answer by Lokni is correct.
Here is the same idea but using Joda-Time 2.8.
long millisSinceEpoch = mar.getEventDate() ;
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ) ; // Or DateTimeZone.UTC
LocalDate localDate = new LocalDate( millisSinceEpoch , zone ) ;
int dayOfMonth = localDate.getDayOfMonth() ;
Given the Date constructor used in the question
Date date = new Date(mar.getEventDate());
The method mar.getEventDate() returns a long that represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.
Java 8 and later
In Java 8, you can extract the day of the month from this value, assuming UTC, with
LocalDateTime.ofEpochSecond(mar.getEventDate(),0,ZoneOffset.UTC).getDayOfMonth();
Note also that the answer given by cletus assume that mar.getEventDate() returns a Date object which is not the case in the question.

Categories

Resources