Java date validation joda time - java

Is there anyway to validate if a given date(yyyy-MM-dd) is a valid date?
It should handle leap year too. eg(2015-02-29) should be invalid.
I'm retrieving the date as a string and putting it into a joda DateTime object.

The previous responses should be fine, but given that the OP specifically asked for a Joda-Time version, this alternative will also work:
#Test
public void test() {
String testDateOk = "2015-02-25"; // Normal date, no leap year
String testDateOk2 = "2016-02-29"; // Edge-case for leap year
String testDateWrong = "2017-02-29"; // Wrong date in a non-leap year
String testDateInvalid = "2016-14-29"; // plain wrong date
assertTrue(isValidDate(testDateOk));
assertTrue(isValidDate(testDateOk2));
assertFalse(isValidDate(testDateWrong));
assertFalse(isValidDate(testDateInvalid));
}
boolean isValidDate(String dateToValidate){
String pattern = "yyyy-MM-dd";
try {
DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
fmt.parseDateTime(dateToValidate);
} catch (Exception e) {
return false;
}
return true;
}

This should work for you, I think (if you want to keep it simple).
You have to do setLenient(false) on a SimpleDateFormat.
public static boolean validateDate(String dateString){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setLenient(false);
try {
sdf.parse(dateString);
return true;
} catch (ParseException ex) {
return false;
}
}

Use SimpleDateFormat
public boolean valiDate(String dateString){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setLenient(false);
try {
Date date = sdf.parse(dateString);
return true;
} catch (ParseException ex) {
return false;
}
}

tl;dr
try { … java.time.LocalDate.parse( input ) … }
catch ( java.time.format.DateTimeParseException e ) { … }
java.time
The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.parse( "2015-02-29" ) ;
To detect invalid inputs, trap for a DateTimeParseException.
String input = "2015-02-29";
try
{
LocalDate ld = LocalDate.parse( input );
System.out.println( "ld.toString(): " + ld ) ;
} catch ( DateTimeParseException e )
{
// … handle exception
System.out.println( e.getLocalizedMessage( ) );
}
Text '2015-02-29' could not be parsed: Invalid date 'February 29' as '2015' is not a leap year
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?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
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.

Related

Manipulating and comparing dates with GregorianCalendar and can't get the code to work properly

I'm struggling to find the error in my code here. paytotal is coming out 0 when it should have a number.
firstDayOfPaycheck is the date Oct. 23rd 2020.
lastDayOfPaycheck is the date Nov. 6 2020.
My Simple date format sdf is "MMM dd, yyyy".
string dateInQuestion passed into runPayroll is "Oct. 31, 2020" which came originally from the same sdf as above.
I'm new to java and haven't dealt with manipulating the calendar like this. It feels like the code below should work.
private void runPayroll(String dateInQuestion, long payForTask){
c.setTime(firstDayOfPaycheck);
//loop through days of paycheck. number from time.compareTo(time2) is negative while time is before time2
while(c.getTime().compareTo(lastDayOfPaycheck)<=0){
if(dateInQuestion != null) {
Date questionDate = sdf.parse(dateInQuestion, new ParsePosition(0));
if (c.getTime().compareTo(questionDate) == 0) {
payTotal += payForTask;
}
}
c.add(Calendar.DAY_OF_YEAR, 1);
}
} //ran inside the query to get the total pay
private void buildPayrollDash(){
String strPayrollAmt = "$" + payTotal;
String startDate = sdf.format(firstDayOfPaycheck);
String trimmedStart = startDate.split(",")[0]; //cuts out the year in the date
String endDate = sdf.format(lastDayOfPaycheck);
String trimmedEnd = endDate.split(",")[0];
int holdBack = sharedPreferences.getInt("payroll holdback", 7);
c.setTime(lastDayOfPaycheck);
c.add(Calendar.DAY_OF_YEAR, holdBack);
String payDate = sdf.format(c.getTime());
String trimmedPaydate = payDate.split(",")[0];
tvPayrollTimefame.setText("Pay from " + trimmedStart + " - " + trimmedEnd);
tvPayrollAmount.setText(strPayrollAmt + " due " + trimmedPaydate);
I'm struggling to find the error in my code here.
You are using terrible date-time classes that were supplanted years ago by the modern java.time classes. Never use Date, Calendar, GregorianCalendar, or their relatives.
firstDayOfPaycheck is the date Oct. 23rd 2020.
Use LocalDate to represent a date without time-of-day and without time zone.
LocalDate firstDayOfPayPeriod = LocalDate.of( 2020 , Month.OCTOBER , 23 ) ;
lastDayOfPaycheck is the date Nov. 6 2020.
You'll find date-time handling much easier if you define your spans-of-time using the Half-Open approach. The beginning is inclusive while the ending is exclusive. So instead of focusing on the last day of the pay period, focus on the first day of the following period.
LocalDate firstDayOfSuccessivePayPeriod = LocalDate.of( 2020 , 11 , 7 ) ;
Tip: You can represent the date range of the pay period as a LocalDateRange object if you add the ThreeTen-Extra library to your Java project.
My Simple date format sdf is "MMM dd, yyyy".
You should not be mixing business logic with localization code. Custom formatting of date-times should only be done for presentation to the user.
When exchanging date-time values textually as data, use the standard ISO 8601 formats. For a date-only value, the standard format is YYYY-MM-DD. The java.time use ISO 8601 formats by default, so no need to specify any formatting pattern.
string dateInQuestion passed into runPayroll is "Oct. 31, 2020" which came originally from the same sdf as above.
LocalDate dateInQuestion = LocalDate.parse( "2020-10-31" ) ;
If you must accommodate an input of formatted date string rather than standard ISO 8601 format, use DateTimeFormatter. This has been covered many many times already on Stack Overflow, so search for more info.
And rather than check for valid data later, check your inputs early in your code. “Fail fast” is the saying.
try
{
LocalDate dateInQuestion = LocalDate.parse( "2020-10-31" );
}
catch ( DateTimeParseException e )
{
// … Handle faulty input.
e.printStackTrace();
}
I'm new to java and haven't dealt with manipulating the calendar like this. It feels like the code below should work.
Your code will be much simpler when using java.time. For one thing, the java.time classes offer convenient isBefore, isAfter, and isEqual methods, so no need for clumsy compareTo calls.
LocalDate firstDayOfPayPeriod = LocalDate.of( 2020 , Month.OCTOBER , 23 );
LocalDate firstDayOfSuccessivePayPeriod = LocalDate.of( 2020 , 11 , 7 );
String input = "2020-10-31";
LocalDate dateInQuestion = null;
try
{
dateInQuestion = LocalDate.parse( input );
}
catch ( DateTimeParseException e )
{
// Handle faulty input.
e.printStackTrace();
}
// Validate dates.
Objects.requireNonNull( firstDayOfPayPeriod );
Objects.requireNonNull( firstDayOfSuccessivePayPeriod );
Objects.requireNonNull( dateInQuestion );
if ( ! firstDayOfPayPeriod.isBefore( firstDayOfSuccessivePayPeriod ) )
{
throw new IllegalStateException( "…" );
}
if ( dateInQuestion.isBefore( firstDayOfPayPeriod ) )
{
throw new IllegalStateException( "…" );
}
if ( ! dateInQuestion.isBefore( firstDayOfSuccessivePayPeriod ) )
{
throw new IllegalStateException( "…" );
}
long payPerDay = 100;
long partialPay = 0;
LocalDate localDate = firstDayOfPayPeriod;
while ( localDate.isBefore( firstDayOfSuccessivePayPeriod ) )
{
if ( localDate.isBefore( dateInQuestion ) )
{
partialPay = ( partialPay + payPerDay );
}
// Set up the next loop.
// Notice that java.time uses immutable objects. So we generate a new object based on another’s values rather than alter (mutate) the original.
localDate = localDate.plusDays( 1 ); // Increment to next date.
}
System.out.println( "Partial pay earned from firstDayOfPayPeriod " + firstDayOfPayPeriod + " to dateInQuestion " + dateInQuestion + " is " + partialPay );
See this code run live on IdeOne.com.
Partial pay earned from firstDayOfPayPeriod 2020-10-23 to dateInQuestion 2020-10-31 is 800
With more experience in programming Java, you may want to do this kind of work using streams. See LocalDate::datesUntil.
By the way, if you want to skip weekends, add something like this:
Set< DayOfWeek > weekend = EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY ) ;
…
if ( weekend.contains( localDate.getDayOfWeek() ) ) { … }
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….

Set the date and time manually - java

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:
In a Java class, store in a specific Object (Calendar is ok, but Date will be also)
In text file, send a human readable date via 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?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
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.

Issue with Calendar calculation that spans 2 calendar years

I'm using a method that calculates the next Monday from a given date string.
public static String getStartOfNextWeek(String DATE){
String format = "dd.MM.yyyy";SimpleDateFormat df = new SimpleDateFormat(format);
Date date = null;
try {
date = df.parse(DATE);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);
int year = cal.get(Calendar.YEAR);
Calendar calendar = new GregorianCalendar();
calendar.clear();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.WEEK_OF_YEAR, week);
//add 8 days to get next weeks Monday
calendar.add(Calendar.DAY_OF_WEEK, 8);
Date startDate = calendar.getTime();
SimpleDateFormat df2 = new SimpleDateFormat("dd.MM.yyyy");
String start = df2.format(startDate);
return start;
This work perfectly fine over a single calendar year, but when I'm passing a value that spans two calendar years problems arise.
For example:
input: 15.12.2014
output: 22.12.2014 CORRECT
input: 22.12.2014
output: 29.12.2014 CORRECT
input: 29.12.2014
output: 6.1.2014 INCORRECT
I realize where the mistake is located, since it takes WEEK_OF_YEAR as "1", but YEAR as "2014", so the output is technically correct. Just wrong for my purpose.
How would i best tell the calendar object that i want the next monday in week 1, but 2015?
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This Answer is left intact as history. See my newer Answer.
Joda-Time
The Joda-Time library, version 2.5, gets the correct answer. And gets it more easily.
// Parse input string.
String input = "29.12.2014";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd.MM.yyyy" );
LocalDate inputLocalDate = formatter.parseLocalDate( input );
// Find desired Monday.
LocalDate possibleMonday = inputLocalDate.withDayOfWeek( DateTimeConstants.MONDAY );
// The possible Monday could be past, present, or future of our input date. Adjust as needed.
LocalDate desiredMonday = null;
if ( possibleMonday.isBefore( inputLocalDate ) || possibleMonday.isEqual( inputLocalDate ) ) {
desiredMonday = possibleMonday.plusWeeks( 1 ); // If the possible Monday is past or present, add a week to get *next* Monday.
} else {
desiredMonday = possibleMonday; // If the possible Monday is future, use it.
}
String output = formatter.print( desiredMonday );
Dump to console.
System.out.println( "input : " + input );
System.out.println( "inputLocalDate : " + inputLocalDate );
System.out.println( "desiredMonday : " + desiredMonday );
System.out.println( "output : " + output );
When run.
input : 29.12.2014
inputLocalDate : 2014-12-29
desiredMonday : 2015-01-05
output : 05.01.2015
There's something weird when combining Date and Calender, when it comes to parsing dates, using only Calender it works great;
String[] dt = dateStr.split("\\.");
GregorianCalendar cal = new GregorianCalendar(Integer.parseInt(dt[2]), (Integer.parseInt(dt[1])-1), Integer.parseInt(dt[0]));
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.clear(Calendar.DAY_OF_WEEK);
cal.add(Calendar.DATE, 7);
System.out.println(cal.get(Calendar.YEAR) + "." + (cal.get(Calendar.MONTH)+1) + "." + cal.get(Calendar.DATE));
Edit: You have to subtract 1 from the month, since calendar expects the months to range from 0 to 11.
(Calendar.JANUARY == 0) //true
tl;dr
LocalDate.parse(
"29.12.2014" ,
DateTimeFormatter.ofPattern( "dd.MM.uuuu" )
).with(
TemporalAdjusters.next( DayOfWeek.MONDAY )
)
2015-01-05
java.time
The modern approach uses the java.time classes.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM.uuuu" )
LocalDate ld = LocalDate.parse( "29.12.2014" , f ) ;
To move to another date, use a TemporalAdjuster implementation found in the TemporalAdjusters class. Specify the desired day-of-week with DayOfWeek enum object. No problem crossing end-of-year/start-of-year.
LocalDate followingMonday = ld.with( TemporalAdjusters.next( DayOfWeek.MONDAY ) ) ;
If you want to use the current date if it is a Monday, use TemporalAdjusters.nextOrSame.
Similar methods provide for previous day-of-week, as well: previous & previousOrSame.
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?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
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.

how to check if one date is after another in java?

I am taking in two dates as command line arguments and want to check if the first one is after the second date. the format of the date it "dd/MM/yyy".
Example: java dateCheck 01/01/2014 15/03/2014
also i will need to check if a third date hardcoded into the program is before the second date.
try {
System.out.println("Enter first date : (dd/MM/yyyy)");
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = sdf.parse(bufferRead.readLine());
System.out.println("Enter second date : (dd/MM/yyyy)");
Date date2 = sdf.parse(bufferRead.readLine());
System.out.println(date1 + "\n" + date2);
if (date1.after(date2)) {
System.out.println("Date1 is after Date2");
} else {
System.out.println("Date2 is after Date1");
}
} catch (IOException e) {
e.printStackTrace();
}
To compare two dates :
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyy");
Date firstDate = sdf.parse("01/01/2014");
Date secondDate = sdf.parse("15/03/2014");
if(firstDate.before(secondDate)){
System.out.println("firstDate < secondDate");
}
else if(firstDate.after(secondDate)){
System.out.println("firstDate > secondDate");
}
else if(firstDate.equals(secondDate)){
System.out.println("firstDate = secondDate");
}
tl;dr
LocalDate ld1 = LocalDate.parse( "01/01/2014" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) ;
LocalDate ld2 = LocalDate.parse( "15/03/2014" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) ;
LocalDate ld3 = LocalDate.of( 2014 , Month.JULY , 1 ) ;
Boolean isFirstDateBeforeSecondDate = ld1.isBefore( ld2 ) ;
Boolean isThirdDateBeforeSecondDate = ld3.isBefore( ld2 ) ;
Boolean result = ( isFirstDateBeforeSecondDate && isThirdDateBeforeSecondDate ) ;
return result ;
Using java.time
The modern approach uses the java.time classes rather than the troublesome old legacy date-time classes (Date, Calendar, etc.).
The LocalDate class represents a date-only value without time-of-day and without time zone.
Define a formatting pattern to match your input strings using the DateTimeFormatter class.
String input = "15/03/2014" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( input , f );
ld.toString(): 2014-03-15
To specify a fixed date, pass year, month, and dayOfMonth. For the month, you may specify a number, sanely numbered 1-12 for January-December (unlike the crazy 0-11 in the legacy classes!). Or you may choose to use the Month enum objects.
LocalDate firstOf2014 = LocalDate.of( 2014 , Month.JANUARY , 1 );
Compare using isBefore, isEqual, or isAfter methods.
Boolean isInputDateBeforeFixedDate = ld.isBefore( firstOf2014 ) ;
isInputDateBeforeFixedDate.toString(): false
ISO 8601
If possible, replace your particular date string format with the standard ISO 8601 format. That standard defines many useful practical unambiguous string formats for date-time values.
The java.time classes use the standard formats by default when parsing/generating strings. You can see examples in the code above. For a date-only value, the standard format is YYYY-MM-DD.
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?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
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.
Use SimpleDateFormat to convert a string to Date.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = sdf.parse("01/01/2017");
Date has before and after methods and can be compared to each other as follows:
if(todayDate.after(historyDate) && todayDate.before(futureDate)) {
// In between
}
For an inclusive comparison:
if(!historyDate.after(todayDate) && !futureDate.before(todayDate)) {
/* historyDate <= todayDate <= futureDate */
}
To read a date and check before:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyy");
try {
Date date1 = sdf.parse(string1);
Date date2 = sdf.parse(string2);
if(date1.before(date2)) {
// do something
}
} catch(ParseException e) {
// the format of the read dates is not the expected one
}

Convert Java string to Time, NOT Date [duplicate]

This question already has answers here:
Parse clock time in java 8
(2 answers)
Closed 6 years ago.
I would like to convert a variable string to a Time type variable, not Date using Java. the string look like this 17:40
I tried using the code below but this instance is a date type variable not time
String fajr_prayertime = prayerTimes.get(0);
DateFormat formatter = new SimpleDateFormat("HH:mm");
fajr_begins = (Date)formatter.parse(fajr_prayertime);
System.out.println(" fajr time " + fajr_begins);
However Netbean complains that I should insert an exception as below;
DateFormat formatter = new SimpleDateFormat("HH:mm");
try {
fajr_begins = (Date)formatter.parse(fajr_prayertime);
} catch (ParseException ex) {
Logger.getLogger(JavaFXApplication4.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(" fajr time " + fajr_begins);
Any idea how I can get the time out of the string above.
java.sql.Time timeValue = new java.sql.Time(formatter.parse(fajr_prayertime).getTime());
You might consider Joda Time or Java 8, which has a type called LocalTime specifically for a time of day without a date component.
Example code in Joda-Time 2.7/Java 8.
LocalTime t = LocalTime.parse( "17:40" ) ;
You might want to take a look at this example:
public static void main(String[] args) {
String myTime = "10:30:54";
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = null;
try {
date = sdf.parse(myTime);
} catch (ParseException e) {
e.printStackTrace();
}
String formattedTime = sdf.format(date);
System.out.println(formattedTime);
}
try {
SimpleDateFormat format = new SimpleDateFormat("hh:mm a"); //if 24 hour format
// or
SimpleDateFormat format = new SimpleDateFormat("HH:mm"); // 12 hour format
java.util.Date d1 =(java.util.Date)format.parse(your_Time);
java.sql.Time ppstime = new java.sql.Time(d1.getTime());
} catch(Exception e) {
Log.e("Exception is ", e.toString());
}
You can use the following code for changing the String value into the time equivalent:
String str = "08:03:10 pm";
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
Date date = (Date)formatter.parse(str);
Hope this helps you.
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:MM");
simpleDateFormat.format(fajr_prayertime);
Joda-Time & java.time
Both Joda-Time and java.time (new in Java 8) offer a LocalTime class to represent a time-of-day without any date or time zone.
Example code, identical code for both java.time and Joda-Time.
LocalTime localTime = new LocalTime( "14:40" );
LocalTime deadline = new LocalTime( "15:30" );
boolean meetsDeadline = localTime.isBefore( deadline );
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
try...
java.sql.Time.valueOf("10:30:54");
String to Time (using an arbitrary time):
String myTime = "10:00:00";
Time startingTime = new Time (myTime);
String to Time (using currentTime):
String currentTime = getCurrentTime();
Time startingTime = new Time (currentTime);
Time to String:
private String getCurrentTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat("kkmmss");
String currentTime = dateFormat.format(System.currentTimeMillis());
return currentTime;
}

Categories