I'm trying to compare a time with the time 24 hours ago.
This is what I have:
public boolean inLastDay(Date aDate) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -1);
Date pastDay = cal.getTime();
if(aDate!= null) {
if(aDate.after(pastDay)){
return true;
} else {
return false;
}
} else {
return false;
}
}
An example of input (these are converted from Strings to Dates):
null (this would return false)
Jul 11 at 19:36:47 (this would return false)
Jul 14 at 19:40:20 (this would return true)
This doesn't seem to be working. It always returns false. Any help would be appreciated!
Answer: In the end I kept getting false because "aDate" had no milliseconds, year, and other values that "pastDay" did.
To fix this I did the following:
SimpleDateFormat sdfStats = new SimpleDateFormat("MMM dd 'at' HH:mm:ss");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -24);
Date yesterdayUF = cal.getTime();
String formatted = sdfStats.format(yesterdayUF);
Date yesterday = null;
try {
yesterday = sdfStats.parse(formatted);
} catch (Exception e) {
}
if(aDate!= null) {
if(aDate.after(yesterday)){
return true;
} else {
return false;
}
} else {
return false;
}
How about using math?
static final long DAY = 24 * 60 * 60 * 1000;
public boolean inLastDay(Date aDate) {
return aDate.getTime() > System.currentTimeMillis() - DAY;
}
So I tested this and it worked (Feel free to remove the debugging things)
Make sure you are working with DateFormat.
public static boolean inLastDay(java.util.Date aDate) {
java.util.Date today = DateFormat.getDateTimeInstance().getCalendar().getTime();
java.util.Date twentyfourhoursbefore = DateFormat.getDateTimeInstance().getCalendar().getTime();
twentyfourhoursbefore.setTime(twentyfourhoursbefore.getTime() - (24*60*60*1000));
System.out.println(DateFormat.getDateTimeInstance().format(today));
System.out.println(DateFormat.getDateTimeInstance().format(twentyfourhoursbefore));
System.out.println(DateFormat.getDateTimeInstance().format(aDate));
if(aDate.after(twentyfourhoursbefore) && aDate.before(today)){
return true;
}
return false;
}
And this is the output:
Using a time within 24 hours:
14.07.1934 22:44:46
13.07.1934 22:44:46
13.07.1934 23:44:46
true
Using a time EXACTLY 24 hours before (it should also work with more than 24 hours):
14.07.1934 22:47:12
13.07.1934 22:47:12
13.07.1934 22:47:12
false
Using a time 24 hours after ATM:
14.07.1934 22:48:20
13.07.1934 22:48:20
15.07.1934 22:48:20
false
Related
This question already has answers here:
Calculate number of weekdays between two dates in Java
(20 answers)
Closed 6 years ago.
StartDate: 2016-05-8 20:16:00;
EndDate: 2016-05-30 20:16:00;
public int saturdaysundaycount(Date d1, Date d2) {
Calendar c1 = Calendar.getInstance();
c1.setTime(d1);
Calendar c2 = Calendar.getInstance();
c2.setTime(d2);
int sundays = 0;
int saturday = 0;
while (c1.after(c2)) {
if (c2.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY || c2.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
sundays++;
saturday++;
c2.add(Calendar.DATE, 1);
c2.add(Calendar.DATE, 1);
}
System.out.println(sundays);
return saturday + sundays;
}
In this function I am trying to get total count of Saturdays and Sundays between two dates. But when I pass the date I get zero as a result. Please point out the mistake and suggest corrections.
It is not advisable to write full program but since you put effort, here is what seems to be working on my system and returning a value of 7.
public class CountWeekends {
public static void main(String[] args){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
int count = 0;
try {
Date d1 = formatter.parse("2016-05-8 20:16:00");
Date d2 = formatter.parse("2016-05-30 20:16:00");
count = saturdaysundaycount(d1,d2);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Count of Sats & Sundays = "+count);
}
public static int saturdaysundaycount(Date d1, Date d2) {
Calendar c1 = Calendar.getInstance();
c1.setTime(d1);
Calendar c2 = Calendar.getInstance();
c2.setTime(d2);
int sundays = 0;
int saturday = 0;
while (! c1.after(c2)) {
if (c1.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY ){
saturday++;
}
if(c1.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
sundays++;
}
c1.add(Calendar.DATE, 1);
}
System.out.println("Saturday Count = "+saturday);
System.out.println("Sunday Count = "+sundays);
return saturday + sundays;
}
Logic: You need to keep increment start date by one day till it
surpasses end date and keep checking day on start date.
The problem is in your while, with this piece of code is working fine for me.
Check the endDate and startDate because I guess that you are sending it in the wrong order.
while (endDate.after(startDate)) {
if (endDate.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY ){
sundays++;
}else if (endDate.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY){
saturday++;
}
endDate.add(Calendar.DATE, -1);
}
Your code does not loop through the days. Please try the following code. In the while loop it loops through all the days between the given fist date and last date. It does this by adding a day to c1 in every iteration until c1 is after c2. This gives number of Saturdays and Sundays between given dates including those two days.
public static int saturdaysundaycount(Date d1, Date d2) {
Calendar c1 = Calendar.getInstance();
c1.setTime(d1);
Calendar c2 = Calendar.getInstance();
c2.setTime(d2);
int sundays = 0;
int saturdays = 0;
while (!c1.after(c2)) {
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd-E");
String formatted = format1.format(c1.getTime());
System.out.println("Current Date C1 : " + formatted);
if (c1.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
sundays++;
} else if (c1.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
saturdays++;
}
c1.add(Calendar.DATE, 1);
}
System.out.println("Sundays : " + sundays);
System.out.println("Saturdays : " + saturdays);
return saturdays + sundays;
}
public static int getNumberofSundays(String d1,String d2) throws Exception{ //object in Date form
Date date1=getDate(d1);
Date date2=getDate(d2);
Calendar c1=Calendar.getInstance();
c1.setTime(date1);
Calendar c2=Calendar.getInstance();
c2.setTime(date2);
int sundays=0;
while(c1.after(c2)){
if(c2.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY){
sundays++;
c2.add(Calendar.DATE,1);
}
}
System.out.println("number of days between 2 dates"+sundays);
return sundays;
}
i have 2 Date (start_date, end_date) with yyyy-MM-dd format and i want to check that if the month between in december 01 - march 31 then do something. For example my start_date is 2015-12-01 or 2016-02-01 and end_date 2016-02-12 then write something.
I have this
public void meethod(){
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = null;
Date endDate = null;
try {
startDate = df.parse(tf_start_date.getText());
endDate = df.parse(tf_end_date.getText());
} catch (ParseException e) {
e.printStackTrace();
}
if( /* what goes here? */ ) {
System.out.println("its between december-march");
} else {
}
}
tf_start_date and tf_end_date is a TextField and the value of TextFields like 2015-02-03
First, you should probably be using Calendar rather than Date. First, you'll need to construct the Calendar using a Calendar.Builder:
Calendar startCal = Calendar.Builder().setInstant(startDate);
Calendar endCal = Calendar.Builder().setInstant(endDate);
Then you can just check their months to see if they are one of the months you're looking for:
int startMonth = startCal.get(Calendar.MONTH);
if (startMonth == Calendar.DECEMBER ||
startMonth == Calendar.JANUARY ||
startMonth == Calendar.FEBRUARY ||
startMonth == Calendar.MARCH)
Similarly with endMonth.
I need to get the full days between two dates in java (the dates are given in Date type) .
For example:
01/01/2015/12:00:00 - 01/02/2015/11:59:00 isn't a full day
and i need to consider daylight savings.
I know that jodatime lib does that but i reached the 65k method limit and i cant use jodatime lib.
i tried the millisecond diff way and the while loop that uses the "before" method:
Android/Java - Date Difference in days
I manage to figure it out:
i used some of this code - https://stackoverflow.com/a/28865648/3873513
and added some of mine:
public static int calcDaysDiff(Date day1, Date day2) {
Date d1 = new Date(day1.getTime());
Date d2 = new Date(day2.getTime());
Calendar date1 = Calendar.getInstance();
date1.setTime(d1);
Calendar date2 = Calendar.getInstance();
date2.setTime(d2);
//checks if the start date is later then the end date - gives 0 if it is
if (date1.get(Calendar.YEAR) >= date2.get(Calendar.YEAR)) {
if (date1.get(Calendar.DAY_OF_YEAR) >= date2.get(Calendar.DAY_OF_YEAR)) {
return 0;
}
}
//checks if there is a daylight saving change between the two dates
int offset = calcOffset(d1, d2);
if (date1.get(Calendar.YEAR) > date2.get(Calendar.YEAR)) {
//swap them
Calendar temp = date1;
date1 = date2;
date2 = temp;
}
return calcDaysDiffAux(date1, date2) + checkFullDay(date1, date2, offset);
}
// check if there is a 24 hour diff between the 2 dates including the daylight saving offset
public static int checkFullDay(Calendar day1, Calendar day2, int offset) {
if (day1.get(Calendar.HOUR_OF_DAY) <= day2.get(Calendar.HOUR_OF_DAY) + offset) {
return 0;
}
return -1;
}
// find the number of days between the 2 dates. check only the dates and not the hours
public static int calcDaysDiffAux(final Calendar day1, final Calendar day2) {
Calendar dayOne = (Calendar) day1.clone(),
dayTwo = (Calendar) day2.clone();
if (dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR)) {
return Math.abs(dayOne.get(Calendar.DAY_OF_YEAR) - dayTwo.get(Calendar.DAY_OF_YEAR));
} else {
int extraDays = 0;
while (dayTwo.get(Calendar.YEAR) > dayOne.get(Calendar.YEAR)) {
dayTwo.add(Calendar.YEAR, -1);
// getActualMaximum() important for leap years
extraDays += dayTwo.getActualMaximum(Calendar.DAY_OF_YEAR);
}
return extraDays - day1.get(Calendar.DAY_OF_YEAR) + day2.get(Calendar.DAY_OF_YEAR);
}
}
public class DateDiff {
public static void main(String[] av) {
SimpleDateFormat myFormat = new SimpleDateFormat("MM/dd/yyyy/HH:mm:ss");
String inputString1 = "01/01/2015/12:00:00";
String inputString2 = "01/02/2015/11:59:00";
try {
Date date1 = myFormat.parse(inputString1);
Date date2 = myFormat.parse(inputString2);
long diff = date2.getTime() - date1.getTime(); // Calculate the different
int days = (int) (diff / (1000*60*60*24)); // This convert milliseconds to days
System.out.println ("Days differ: " + days);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The following code will calculate the two dates given, the result print is:
Days differ: 0
I have a start date and end date in database like below.
start date:01/06/2014 end date:30/06/2014
start date:01/07/2014 end date:30/09/2014
start date:01/10/2014 end date:31/03/2015
if i enter the date range
start date 02/06/2014 end date 01/02/2015
the output has to be.
28 days, in 1st slab date range
2 months, 29 days, in 2nd slab date range
4 months in 3rd slab date range
how to achieve this in java.
Thanks in advance.
This question is difficult to answer accurately. I believe this is what you really want,
// get the minimum of any number of dates.
private static Date getMinimum(Date... dates) {
if (dates == null)
return null;
Date min = dates[0];
for (Date d : dates) {
if (d.compareTo(min) < 0) {
min = d;
}
}
return min;
}
// get the maximum of any number of dates.
private static Date getMaximum(Date... dates) {
if (dates == null)
return null;
Date max = dates[0];
for (Date d : dates) {
if (d.compareTo(max) > 0) {
max = d;
}
}
return max;
}
public static String getDateDiff(Date startDate,
Date endDate) {
StringBuilder sb = new StringBuilder();
Calendar start = Calendar.getInstance();
start.setTime(getMinimum(startDate, endDate));
Calendar end = Calendar.getInstance();
end.setTime(getMaximum(startDate, endDate));
if (start.compareTo(end) < 0) {
int monthCount = 0;
int dayCount = 0;
while (start.compareTo(end) < 0) {
start.add(Calendar.MONTH, 1);
if (start.compareTo(end) < 0) {
monthCount++;
}
}
start = Calendar.getInstance();
start.setTime(getMinimum(startDate, endDate));
start.add(Calendar.MONTH, monthCount);
while (start.compareTo(end) < 0) {
start.add(Calendar.DAY_OF_MONTH, 1);
if (start.compareTo(end) < 0) {
dayCount++;
}
}
if (monthCount > 0) {
sb.append(String.format("%d months",
monthCount));
}
if (dayCount > 0) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(String.format("%d days", dayCount));
}
} else {
sb.append("0 days");
}
return sb.toString();
}
public static void main(String[] args) {
String[] input = { "01/06/2014-30/06/2014", //
"01/07/2014-30/09/2014", //
"01/10/2014-31/03/2015", //
"02/06/2014-01/02/2015", };
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
for (String str : input) {
String sArr[] = str.split("-");
try {
Date start = df.parse(sArr[0]);
Date end = df.parse(sArr[1]);
System.out.printf("start: %s, end: %s - diff: %s\n", sArr[0],
sArr[1], getDateDiff(start, end));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
The output is
start: 01/06/2014, end: 30/06/2014 - diff: 28 days
start: 01/07/2014, end: 30/09/2014 - diff: 2 months, 28 days
start: 01/10/2014, end: 31/03/2015 - diff: 5 months, 29 days
start: 02/06/2014, end: 01/02/2015 - diff: 7 months, 29 days
Please check whether below code is helpful. I am using this.
public String getDifference(Date date1, Date date2){
long difference = date2.getTime() - date1.getTime();
long diffDays = difference / (24 * 60 * 60 * 1000);
return (diffDays/30)+" months and "+(diffDays%30)+" days";
}
public int monthsBetweenDates(Date startDate, Date endDate){
Calendar start = Calendar.getInstance();
start.setTime(startDate);
Calendar end = Calendar.getInstance();
end.setTime(endDate);
int monthsBetween = 0;
int dateDiff = end.get(Calendar.DAY_OF_MONTH)-start.get(Calendar.DAY_OF_MONTH);
if(dateDiff<0) {
int borrrow = end.getActualMaximum(Calendar.DAY_OF_MONTH);
dateDiff = (end.get(Calendar.DAY_OF_MONTH)+borrrow)-start.get(Calendar.DAY_OF_MONTH);
monthsBetween--;
if(dateDiff>0) {
monthsBetween++;
}
}
else {
monthsBetween++;
}
monthsBetween += end.get(Calendar.MONTH)-start.get(Calendar.MONTH);
monthsBetween += (end.get(Calendar.YEAR)-start.get(Calendar.YEAR))*12;
return monthsBetween;
}
I have some documents and its created time is in milliseconds.
I need to separate them as Today, Yesterday, Last 7 Days, Last 30 Days, More than 30 Days.
I used the following code:convertSimpleDayFormat(1347022979786);
public static String convertSimpleDayFormat(Long val) {
long displayTime = System.currentTimeMillis() - val;
displayTime = displayTime/86400000;
String displayTimeVal = "";
if(displayTime <1)
{
displayTimeVal = "today";
}
else if(displayTime<2)
{
displayTimeVal = "yesterday";
}
else if(displayTime<7)
{
displayTimeVal = "last7days";
}
else if(displayTime<30)
{
displayTimeVal = "last30days";
}
else
{
displayTimeVal = "morethan30days";
}
return displayTimeVal;
}
I am subtracting the current time and passing the milliseconds and converting to one day.
But the issue I'm facing is, I couldn't calculate the exact time for the date in milliseconds.
I want to calculate for Today as: From Midnight 00:00 to Midnight 24:00. (Exactly for 24 hours.)
Similarly I want to exactly convert the Milliseconds into Today, Yesterday, Last 7 days, Last 30 Days and More than 30 Days.
private static Calendar clearTimes(Calendar c) {
c.set(Calendar.HOUR_OF_DAY,0);
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND,0);
c.set(Calendar.MILLISECOND,0);
return c;
}
public static String convertSimpleDayFormat(long val) {
Calendar today=Calendar.getInstance();
today=clearTimes(today);
Calendar yesterday=Calendar.getInstance();
yesterday.add(Calendar.DAY_OF_YEAR,-1);
yesterday=clearTimes(yesterday);
Calendar last7days=Calendar.getInstance();
last7days.add(Calendar.DAY_OF_YEAR,-7);
last7days=clearTimes(last7days);
Calendar last30days=Calendar.getInstance();
last30days.add(Calendar.DAY_OF_YEAR,-30);
last30days=clearTimes(last30days);
if(val >today.getTimeInMillis())
{
return "today";
}
else if(val>yesterday.getTimeInMillis())
{
return "yesterday";
}
else if(val>last7days.getTimeInMillis())
{
return "last7days";
}
else if(val>last30days.getTimeInMillis())
{
return "last30days";
}
else
{
return "morethan30days";
}
}
It's a small hack, not severely tested. Use at own risk. I've made it extensible so you can add new durations.
public static String prettyTimeStamp(long timeStamp) {
Calendar c = Calendar.getInstance();
c.clear(Calendar.HOUR_OF_DAY);
c.clear(Calendar.MINUTE);
c.clear(Calendar.SECOND);
c.clear(Calendar.MILLISECOND);
long today = c.getTimeInMillis();
final long oneDay = 24 * 60 * 60 * 1000L;
final long[] durations = new long[] { today - oneDay, today,
today + 7 * oneDay, today + 30 * oneDay };
final String[] labels = "Yesterday,Today,Last 7 days,Last 30 Days,More than 30 Days"
.split(",");
int pos = Arrays.binarySearch(durations, timeStamp);
return labels[pos < 0 ? ~pos : pos];
}
By the way, you should really just use a Library like PrettyTime