How to calculate properly actual month count between 2 dates? - java

I have followed method getDiffDateMap that calculates difference between 2 dates and returns Map of Integers that represent milliseconds, seconds, minutes, hours, days, months and years respectively.
public static Map<Integer, String> getDiffDateMap(String dateA, String dateB) {
Calendar cal = Calendar.getInstance();
Map<Integer,String> out = new LinkedHashMap<Integer, String>();
long timeInMillA = 0;
long timeInMillB = 0;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date convertedDateA;
Date convertedDateB;
try {
convertedDateA = dateFormat.parse(dateA);
cal.setTime(convertedDateA);
timeInMillA = cal.getTimeInMillis();
convertedDateB = dateFormat.parse(dateB);
cal.setTime(convertedDateB);
timeInMillB = cal.getTimeInMillis();
} catch (ParseException e) {
e.printStackTrace();
}
long mili = timeInMillB - timeInMillA;
long sec = mili/1000;
long min = sec/60;
long hour = min/60;
long day = hour/24;
long week = day/7;
long month = day/31; // ????
long year = month/12;
out.put(7, mili + "");
out.put(6, sec + "");
out.put(5, min + "");
out.put(4, hour + "");
out.put(3, day + "");
out.put(2, week + "");
out.put(1, month + "");
out.put(0, year + "");
return out;
}
My problem is to calculate month from actual day count:
long month = day/31; // or 30
For example:
Map<Integer,String> out = getDiffInMillsec("2012-9-01 20:9:01", "2012-10-01 20:10:01");
System.out.println(Arrays.asList(out));
I get output: [{7=2592060000, 6=2592060, 5=43201, 4=720, 3=30, 2=4, 1=0, 0=0}] where 1 is month count and its 0. because difference is 30 days only. What flow need I add to fix this problem? Any suggestions?

I have followed method getDiffDateMap that calculates difference between 2 dates and returns Map of Integers that represent milliseconds, seconds, minutes, hours, days, months and years respectively.
Don't reinvent the wheel :)
Joda Time has code to do all this and more. For example:
LocalDateTime start = ...;
LocalDateTime end = ...;
Period difference = new Period(start, end, PeriodType.yearMonthDayTime());
int months = difference.getMonths(); // etc
Note that you can't get at the number of months when you've just converted the different to a number of milliseconds - as the number of months will depend on the start/end date. (30 days may or may not be a month, for example...)
I'd strongly advise you to use Joda Time throughout your Java code, in preference to java.util.*. It's a much better API, and one which will hopefully mean you rarely-if-ever need to write your own date/time handling code.

I woud suggest to use JodaTime#Months
This has a functions such as :
static Months monthsBetween(ReadableInstant start, ReadableInstant end)
Creates a Months representing the number of whole months between the two specified datetimes.
static Months monthsBetween(ReadablePartial start, ReadablePartial end)
Creates a Months representing the number of whole months between the two specified partial datetimes.

I just want to conclude all what we talked before and with help of Jon Skeet, here is an answer, I used JodaTime and new Period per date value:
import org.joda.time.LocalDateTime;
import org.joda.time.Period;
import org.joda.time.PeriodType;
....
public static Map<Integer, String> getDateTimeDiffMap(String dateA, String dateB) {
Calendar cal = Calendar.getInstance();
Map<Integer,String> out = new LinkedHashMap<Integer, String>();
long timeInMillA = 0;
long timeInMillB = 0;
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Date convertedDateA;
Date convertedDateB;
try {
convertedDateA = dateFormat.parse(dateA);
cal.setTime(convertedDateA);
timeInMillA = cal.getTimeInMillis();
convertedDateB = dateFormat.parse(dateB);
cal.setTime(convertedDateB);
timeInMillB = cal.getTimeInMillis();
} catch (ParseException e) {
e.printStackTrace();
}
LocalDateTime startA = new LocalDateTime(timeInMillA);
LocalDateTime startB = new LocalDateTime(timeInMillB);
Period difference = new Period(startA, startB, PeriodType.days());
int day = difference.getDays();
difference = new Period(startA, startB, PeriodType.months());
int month = difference.getMonths();
difference = new Period(startA, startB, PeriodType.years());
int year = difference.getYears();
difference = new Period(startA, startB, PeriodType.weeks());
int week = difference.getWeeks();
difference = new Period(startA, startB, PeriodType.hours());
int hour = difference.getHours();
difference = new Period(startA, startB, PeriodType.minutes());
long min = difference.getMinutes();
difference = new Period(startA, startB, PeriodType.seconds());
long sec = difference.getSeconds();
//difference = new Period(startA, startB, PeriodType.millis());
long mili = timeInMillB - timeInMillA;
out.put(7, mili + "");
out.put(6, sec + "");
out.put(5, min + "");
out.put(4, hour + "");
out.put(3, day + "");
out.put(2, week + "");
out.put(1, month + "");
out.put(0, year + "");
return out;
}
For example for "01-09-2012 20:9:01", "01-10-2012 20:9:01" I get output:
year=0;
month = 1;
day=30;
hour=720;
...

java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(getDiffDateMap("2012-9-01 20:9:01", "2012-10-01 20:10:01"));
}
public static Map<Integer, String> getDiffDateMap(String dateA, String dateB) {
Map<Integer, String> out = new LinkedHashMap<Integer, String>();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("u-M-d H:m:s", Locale.ENGLISH);
LocalDateTime ldtA = LocalDateTime.parse(dateA, dtf);
LocalDateTime ldtB = LocalDateTime.parse(dateB, dtf);
out.put(7, String.valueOf(ChronoUnit.MILLIS.between(ldtA, ldtB)));
out.put(6, String.valueOf(ChronoUnit.SECONDS.between(ldtA, ldtB)));
out.put(5, String.valueOf(ChronoUnit.MINUTES.between(ldtA, ldtB)));
out.put(4, String.valueOf(ChronoUnit.HOURS.between(ldtA, ldtB)));
out.put(3, String.valueOf(ChronoUnit.DAYS.between(ldtA, ldtB)));
out.put(2, String.valueOf(ChronoUnit.WEEKS.between(ldtA, ldtB)));
out.put(1, String.valueOf(ChronoUnit.MONTHS.between(ldtA, ldtB)));
out.put(0, String.valueOf(ChronoUnit.YEARS.between(ldtA, ldtB)));
return out;
}
}
Output:
{7=2592060000, 6=2592060, 5=43201, 4=720, 3=30, 2=4, 1=1, 0=0}
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

try {
String user = request.getParameter("uname");
out.println(user);
String pass = request.getParameter("pass");
out.println(pass);
java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
Class.forName( "com.mysql.jdbc.Driver" );
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/trans","root","root" ) ;
Statement st = conn.createStatement();
String sql = "insert into purch (cd,cust,dateof) values('" + user + "','" + pass + "', '" + sqlDate + "')";
st.executeUpdate(sql);
Date date = new Date();
String modifiedDate= new SimpleDateFormat("-MM-").format(date);
String dd = modifiedDate.toString();
String da = "ai";
out.println(dd);
PreparedStatement statement = conn.prepareStatement("select * from purch where dateof LIKE ? and cd = ?");
statement.setString(1,"%" + dd + "%");
statement.setString(2,"" + da + "");
ResultSet rs = statement.executeQuery();
if(rs != null) {
while(rs.next()) {
out.println(rs.getString("cd"));
out.println(rs.getString("cust"));
out.println(rs.getString("dateof"));
}
}
}catch(Exception e) {
System.out.println(e.toString());
}

Related

Adjusting time correctly using DateTimeFormatter

I am creating an appointment app that has the capability to view monthly/weekly. The standard view, is able to show correct times in HH:mm, only between 9:00 - 17:00 . However, the monthly/weekly I can't convert and shows in full 24 hour time.
For the monthly I have:
public LocalTime getTime() {
return time;
}
#FXML
private void viewByMonthHandler(ActionEvent event) {
DataProvider.getAppointmentsByMonth().clear();
DataProvider.getAppointmentsByWeek().clear();
if(viewByMonthRadioButton.isSelected()) {
// I was using these two to try and convert
//DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
//DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("MMMM HH:mm");
Calendar cal = Calendar.getInstance();
String month = new SimpleDateFormat("MMMM").format(cal.getTime());
DataProvider.setMonthlyView(month);
}
sortAppointment();
viewByComboBox.setItems(viewByMonth);
}
I have tried :
String month = new DateTimeFormatter.ofPattern("MMMM HH:mm").format(cal.getTime());
and:
String month = new SimpleDateFormat("MMMM").format(timeFormat);
error:
Caused by: java.lang.IllegalArgumentException: Cannot format given Object as a Date
for the weekly I have:
#FXML
private void viewByWeekHandler(ActionEvent event) {
DataProvider.getAppointmentsByMonth().clear();
DataProvider.getAppointmentsByWeek().clear();
if(viewByWeekRadioButton.isSelected()) {
DataProvider.setWeeklyView(0);
}
sortAppointment();
viewByComboBox.setItems(viewByWeek);
}
setWeeklyView:
public static void setWeeklyView (int weekForReference) {
try {
ArrayList<Integer> selectedAppointmentsByWeek = new ArrayList<>();
Statement statement = DBConnection.getConnection().createStatement();
ResultSet weeklyAppointments = statement.executeQuery("SELECT appointmentId from appointment where year(start) = YEAR(date_add(curdate(), interval " + weekForReference + " WEEK)) and weekofyear(start) = weekofyear(date_add(curdate(),interval " + weekForReference + " WEEK));");
while(weeklyAppointments.next()) {
selectedAppointmentsByWeek.add(weeklyAppointments.getInt(1));
}
for(int appointmentId : selectedAppointmentsByWeek) {
ResultSet selectAppointment = statement.executeQuery("SELECT customer.customerName, customer.customerId, contact, title, type, location, description, start, end FROM appointment JOIN customer ON customer.customerId = appointment.customerId WHERE appointmentId =" + appointmentId);
selectAppointment.next();
Appointment appointment = new Appointment();
String customerName = selectAppointment.getString(1);
int customerId = selectAppointment.getInt(2);
String contact = selectAppointment.getString(3);
String title = selectAppointment.getString(4);
String type = selectAppointment.getString(5);
String location = selectAppointment.getString(6);
String description = selectAppointment.getString(7);
String start = selectAppointment.getString(8);
String end = selectAppointment.getString(9);
appointment.setCustomerName(customerName);
appointment.setContact(contact);
appointment.setTitle(title);
appointment.setType(type);
appointment.setLocation(location);
appointment.setDescription(description);
appointment.setStart(start);
appointment.setEnd(end);
appointmentsByWeek.add(appointment);
}
}
catch(SQLException ex) {
System.out.println("Error " + ex.getMessage());
}
}
The setMonthlyView is almost identical, just replacing weekly with monthly. How could I go about formatting these so they are no longer HH:mm:ss.S and in between 9:00-17:00? I have taken the advice previously given to me for the little parts, and still can't figure it out. Thank you so much for taking the time to read and help.
Do one of these do what you want.
12 hour
String localDateTime12Hour =
LocalDateTime.now().format(DateTimeFormatter.ofPattern("MMMM hh:mm a"));
System.out.println(localDateTime12Hour);
24 hour
String localDateTime24Hour =
LocalDateTime.now().format(DateTimeFormatter.ofPattern("MMMM HH:mm"));
System.out.println(localDateTime24Hour);
Prints
July 06:11 PM
July 18:11
Use HH for 24 hour
Use hh for 12 hour (the a provides AM or PM)
Remember to use LocalDateTime and not LocalTime when specifying formatter attributes like MMMM. You are returning a LocalTime object in your getTime() method. And I would avoid using Calendar and Date as they are outmoded. Use classes from the java.time package.

Calculating the time difference between two time stamp object - java

I am having java.sql.date and java.sql.time objects, I need to find the time duration between the dates.
So i am creating java.sql.timestamp object by using above date and time object
Timestamp timestamp1 = new Timestamp(StartDate.getYear(),
StartDate.getMonth(), StartDate.getDay(),
StartTime.getHours(), StartTime.getMinutes(), 00,
00);
Here is mycode
String date = "2010-01-05";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date3 = null;
try {
date3 = sdf1.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
Date StartDate = new Date(date3.getTime());
System.out.println("Date " + StartDate);
String date2 = "2010-01-06";
java.util.Date date4 = null;
try {
date4 = sdf1.parse(date2);
} catch (ParseException exception) {
exception.printStackTrace();
}
Date EndDate = new Date(date4.getTime());
System.out.println("Date " + EndDate);
String time = "01:00";
DateFormat formatter = new SimpleDateFormat("HH:mm");
java.sql.Time StartTime = null;
try {
StartTime = new java.sql.Time(formatter.parse(time).getTime());
} catch (ParseException exception2) {
exception2.printStackTrace();
}
System.out.println("TIMEEEEEEEEEE====" + StartTime);
String time2 = "02:00";
java.sql.Time EndTime = null;
try {
EndTime = new java.sql.Time(formatter.parse(time2).getTime());
} catch (ParseException exception3) {
exception3.printStackTrace();
}
System.out.println("TIMEEEEEEEEEE====" + EndTime);
Timestamp timestamp1 = new Timestamp(StartDate.getYear(),
StartDate.getMonth(), StartDate.getDay(),
StartTime.getHours(), StartTime.getMinutes(), 00,
00);
Timestamp timestamp2 = new Timestamp(EndDate.getYear(),
EndDate.getMonth(), EndDate.getDay(),
EndTime.getHours(), EndTime.getMinutes(), 00, 00);
long milliseconds = timestamp2.getTime() - timestamp1.getTime();
int seconds = (int) milliseconds / 1000;
// calculate hours minutes and seconds
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
seconds = (seconds % 3600) % 60;
System.out.println(hours+"h:"+minutes+"m:"+"00s");
Test case
when I give date as 2010-01-05 and date2 as 2010-01-06 I am getting output as below
Date 2010-01-05
Date 2010-01-06
TIMEEEEEEEEEE====01:00:00
TIMEEEEEEEEEE====02:00:00
25h:0m:00s
when I give date as 2010-01-05 and date2 as 2010-01-11 I am getting output in negative value as below
Date 2010-01-05
Date 2010-01-11
TIMEEEEEEEEEE====01:00:00
TIMEEEEEEEEEE====02:00:00
-23h:0m:00s
Help me to correct if I am doing something wrong.
Thanks in advance.
Manual time calculation:-
Converts Date in milliseconds (ms) and calculate the differences between two dates, with following rules :
1000 milliseconds = 1 second
60 seconds = 1 minute
60 minutes = 1 hour
24 hours = 1 day
Sample Example:-
package com.dps2.practice.dyuti;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDifferentExample {
public static void main(String[] args) {
String dateStart = "08/11/2016 09:29:58";
String dateStop = "08/12/2016 10:31:48";
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
The problem with your calculation is this: StartDate.getDay() etc.
getDay() will return the number of day of the week (read the JavaDoc) and not the day of the month. You'll need to use getDate() instead.
To illustrate the problem using your values: 2010-01-05 will return 2 for getDay() and thus you are getting 2010-01-02 as your timestamp. 2010-01-11 will return 1 for getDay() (it's 6 days later, i.e. (2 + 6) % 7 = 1) and hence your second timestamp becomes 2010-01-01. Now the second timestamp is before the first and hence you get a negative value.
However, as I already stated in my comments you should try and use some library or at least the non-deprecated built-in functionality for those calculations to save you a lot of headaches (I suggest you watch this video to get an idea of the challenges: https://youtube.com/watch?v=-5wpm-gesOY ).
The java.sql date-time classes are meant only for exchanging data with databases. Do not use them for business logic. Also, they are part of the troublesome, poorly designed, and confusing old legacy date-time classes. Avoid them all.
java.time
The java.time classes built into Java 8 and later supplant the old classes you are using. Much simpler now.
LocalDate ld = LocalDate.parse ( "2010-01-06" );
LocalTime lt = LocalTime.parse ( "01:00" );
LocalDateTime earlier = LocalDateTime.of ( ld , lt );
LocalDateTime later = earlier.plusHours ( 7 );
The Duration class represents a span of time as a total number of seconds and nanoseconds. Its toString method generates a String in the standard ISO 8601 format PnYnMnDTnHnMnS. This format uses P to mark the beginning, and the T to separate year-months-days from hours-minutes-seconds portion. The Duration and Period classes can both parse and generate such Strings.
Duration duration = Duration.between ( earlier , later );
In Java 8, Duration class inexplicably lacks getter methods for each part: days, hours, minutes, seconds, fraction-of-second. Java 9 rectifies this omission with new getPart methods.
Dump to console.
System.out.println ( "earlier: " + earlier + " | later: " + later + " | duration: " + duration );
earlier: 2010-01-06T01:00 | later: 2010-01-06T08:00 | duration: PT7H
Time zone
Be aware that your inputs lacked any information about offset-from-UTC or time zone. So the math seen above is performed assuming generic 24-hour days. Real-world anomalies such as Daylight Saving Time (DST) are ignored.
If you did indeed intend time zones, assign them via the atZone method to instantiate OffsetDateTime or ZonedDateTime objects.
That's a complicated code you have in your question there. You can make it quite easy by using java.util.concurrent.TimeUnit class.
Output
Date Tue Jan 05 00:00:00 UTC 2010
Date Wed Jan 06 00:00:00 UTC 2010
difference is:
24 hours : 1440 minutes : 86400 seconds
Code
import java.util.*;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
public class HelloWorld {
public static void main(String[] args) {
String date = "2010-01-05";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date3 = null;
try {
date3 = sdf1.parse(date);
} catch (Exception e) {
e.printStackTrace();
}
Date StartDate = new Date(date3.getTime());
System.out.println("Date " + StartDate);
String date2 = "2010-01-06";
java.util.Date date4 = null;
try {
date4 = sdf1.parse(date2);
} catch (Exception exception) {
exception.printStackTrace();
}
Date EndDate = new Date(date4.getTime());
System.out.println("Date " + EndDate);
long dateStart = StartDate.getTime(), dateStop = EndDate.getTime();
long diff = dateStop - dateStart;
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(diff);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(diff);
long diffInHours = TimeUnit.MILLISECONDS.toHours(diff);
System.out.println("\n\ndifference is:\n");
System.out.println(diffInHours + " hours : " + diffInMinutes + " minutes : " + diffInSeconds + " seconds");
}
}

Calculate no of days between two dates in java [duplicate]

This question already has answers here:
Android/Java - Date Difference in days
(18 answers)
Closed 6 years ago.
I need to calculate number of days between two dates and I am using below code. problem is it is returning me 2 but actually it should return 3 because difference between 30 june 2016 to 27 june is 3. can you please help where it should include current date as well in difference?
public static long getNoOfDaysBtwnDates(String expiryDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
long diff = 0;
long noOfDays = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Date createdDate = new Date();
diff = expDate.getTime() - createdDate.getTime();
noOfDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
long a = TimeUnit.DAYS.toDays(noOfDays);
// logger.info("No of Day after difference are - " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
System.out.println(a);
System.out.println(noOfDays);
} catch (ParseException e) {
e.printStackTrace();
}
return noOfDays;
}
expiry date is 2016-06-30 and current date is 2016-06-27
Reason is, you are not subtracting two dates with same time format.
Use Calendar class to change the time as 00:00:00 for both date and you will get exact difference in days.
Date createdDate = new Date();
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 0);
time.set(Calendar.MINUTE, 0);
time.set(Calendar.SECOND, 0);
time.set(Calendar.MILLISECOND, 0);
createdDate = time.getTime();
More explaination in Jim Garrison' answer
Why not use LocalDate?
import java.time.LocalDate;
import static java.time.temporal.ChronoUnit.DAYS;
long diffInDays(LocalDate a, LocalDate b) {
return DAYS.between(a, b);
}
The problem is that
Date createdDate = new Date();
sets createdDate to the current instant, that is, it includes the current time as well as the date. When you parse a string using the given format, the time is initialized to 00:00:00.
Let's say you ran this at exactly 18:00 local time, you end up with
createdDate = 2016-06-27 18:00:00.000
expDate = 2016-06-30 00:00:00.000
The difference is 2 days 6 hours, not 3 days.
You should be using the newer java.time.* classes from Java 8. There is a class LocalDate that represents dates without time-of-day. It includes methods for parsing using a format, and LocalDate.now() to get the current date, as well as methods for calculating intervals between LocalDate instances.
Using the Calendar.get(Calendar.DAY_OF_MONTH) as pointed out by python:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
String expiryDate ="2016-06-30";
int diff = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Calendar cal = Calendar.getInstance();
int today = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(expDate);
diff = cal.get(Calendar.DAY_OF_MONTH)- today;
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(diff);

Using Java SimpleDateFormat to find max date

I haven't programmed in Java for many years, but I now have to change a program I wrote some time ago. In this program I need to read a QIF file and find the qif record with the maximum date (Dmm-dd-yyyy).
I could not get this to work in my program so I wrote a simple test to demonstrate the problem I am having. I think there are other ways to do this, like lists and collections. But I still want to know why using SimpleDateFormat won't work. Notice in the output that this method produces the max for July but seems to ignore all August dates.
Thanks, Mike
import java.text.SimpleDateFormat;
import java.util.Date;
class DateParser {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("mm-dd-yyyy");
Date nextDate = null;
Date maxDate = null;
String nextStrDate = null;
String maxStrDate = null;
//Fill date array.
String date[] = {"07-14-2014","07-22-2014","07-31-2014",
"08-01-2014","08-04-2014","08-06-2014"};
try {
//Start with early maximum date.
maxDate = sdf.parse("01-01-1800");
// Find Max date in array.
for (int i=0; i<6; ++i) {
nextStrDate = date[i];
nextDate = sdf.parse(nextStrDate);
if(nextDate.after(maxDate)){
maxStrDate = nextStrDate;
maxDate = nextDate;
}
System.out.println( "Next Date = " + nextStrDate);
}
System.out.println("\nMax Date = " + maxStrDate);
} catch (Exception e) {
System.out.println("Got error:" + e);
}
}
}
OUTPUT
Next Date = 07-14-2014
Next Date = 07-22-2014
Next Date = 07-31-2014
Next Date = 08-01-2014
Next Date = 08-04-2014
Next Date = 08-06-2014
Max Date = 07-31-2014
From the Java Docs....
m Minute in hour
What you want is
M Month in year
Change mm-dd-yyyy to MM-dd-yyyy
You format is incorrect, this
SimpleDateFormat sdf = new SimpleDateFormat("mm-dd-yyyy");
should be
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
because (per the SimpleDateFormat documentation),
Letter Date or Time Component Presentation Examples
...
M Month in year Month July; Jul; 07
...
m Minute in hour Number 30

How to find the days between dates using my code?

Below is my code which checks the date which is stored in database with the current system date and calculates the days and if that days is lesser than the 180 days it will print something else print nothing,this code works great in an normal java program(with out using swings concept) if it is used with the swing program i changed the sql query to check get the date from the database based on the department and staff names which is entered in the text fields,i coded this code inside an jbutton,in the output it just prints the current system date but not calculates the days between the selected date and the current system dates,friends this is the problem am facing kindly need your help friends....thanks in advance..
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/leave", "root", "");
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery("select * from staff where depmt='" + txt1 + "' AND staffs='" + txt2 + "'");
Calendar javaCalendar = null;
String currentDate = "";
javaCalendar = Calendar.getInstance();
currentDate = javaCalendar.get(Calendar.DATE) + "/" + (javaCalendar.get(Calendar.MONTH) + 1) + "/" + javaCalendar.get(Calendar.YEAR);
int cdate = javaCalendar.get(Calendar.DATE);
int cmonth = (javaCalendar.get(Calendar.MONTH) + 1);
int cyear = javaCalendar.get(Calendar.YEAR);
int z = 0;
int date = 0, month = 0, year = 0;
System.out.println("Current Date\t" + currentDate);
System.out.println("\n");
while (rs.next()) {
date = rs.getInt(3);
month = rs.getInt(4);
year = rs.getInt(5);
System.out.println("Random Date\t" + date + "/" + month + "/" + year + "\n");
int d = (date - cdate);
int m = month - cmonth;
int y = year - cyear;
int d1 = java.lang.Math.abs(d);
int d2 = java.lang.Math.abs(m);
int d3 = java.lang.Math.abs(y);
z = d1 + (d2 * 30) + (d3 * 365);
if (z >= 180) {
System.out.println("something");
0
} else {
System.out.println("nothing");
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
//e.printStackTrace();
}
// TODO add your handling code here:
}
You should really use prepared statements cause this way your query is prone to sql injections.
Date formatter insted of concating string for currentdate
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(todaysDate);
Also it seems like your not closeing the connection that may be another issue.
Is there any reason for storeing the date in 3 separate columns?
Your algorithm to calculate the day difference between two dates is broken. It does not take in account different month lengths or leap years.
Unfortunately Java Calendar does not offer this feature at all. So either you apply your own homegrown algorithm (not easy, but in web there are some sources how to map a gregorian date to epoch days) or you use JodaTime like this way:
LocalDate db = new LocalDate(year, month, date);
int days = Days.daysBetween(db, LocalDate.now()).getDays();
Note that the result will be negative if db date is in the future. After all you can greatly shorten your code and abandon all Calendar stuff which is very bad for calculations of durations.
try this:
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = df.parse("14/02/2014");
Date date2 = df.parse("08/03/2014");
int days = Days.daysBetween(date1, date2).getDays();
Try this, by changing return value from millisecond to day.
public static int daysBetween(Date dateFrom, Date dateTo){
return (int)( (dateTo.getTime() - dateFrom.getTime()) / (1000 * 60 * 60 * 24));
}
Start Of Day
If you start with a mid-afternoon date-time object, go back 180 days by calculating seconds * minutes * hours * 180, you'll end up excluding the date-times earlier in that day 180 ago whereas I suppose you would want to include them. You should pay attention to when the day begins.
Time Zone
Both the question and other answers ignore the issue of time zone. Time zone defines the beginning of a day. Given the point about start of day (above), time zone is a related component.
Avoid java.util.Date & .Calendar
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them. Instead use either Joda-Time or the new java.time package in Java 8.
Joda-Time
Here is some example code using Joda-Time 2.3.
Note that while a Joda-Time DateTime object is similar to a java.util.Date, a DateTime does truly know its own assigned time zone.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTimeInQuestion = new DateTime( 2013, 6, 5, 4, 3, 2, timeZone );
DateTime now = new DateTime( timeZone );
DateTime hundredEightyDaysAgo = now.minusDays( 180 ).withTimeAtStartOfDay();
boolean isExpired = dateTimeInQuestion.isBefore( hundredEightyDaysAgo );
Dump to console…
System.out.println( "dateTimeInQuestion: " + dateTimeInQuestion );
System.out.println( "now: " + now );
System.out.println( "hundredEightyDaysAgo: " + hundredEightyDaysAgo );
System.out.println( "isExpired: " + isExpired );
When run…
dateTimeInQuestion: 2013-06-05T04:03:02.000+02:00
now: 2014-03-10T07:34:26.937+01:00
hundredEightyDaysAgo: 2013-09-11T00:00:00.000+02:00
isExpired: true

Categories

Resources