I have two Calendar objects, and I want to check what is the difference between them, in hours.
Here is the first Calendar
Calendar c1 = Calendar.getInstance();
And the second Calendar
Calendar c2 = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
c2.setTime(sdf.parse("Sun Feb 22 20:00:00 CET 2015"));
Now lets say that c1.getTime() is: Fri Feb 20 20:00:00 CET 2015 and c2.getTime() is Sun Feb 22 20:00:00 CET 2015.
So is there any code that would return the difference between first and second Calendar in hours? In my case it should return 48.
You can try the following:
long seconds = (c2.getTimeInMillis() - c1.getTimeInMillis()) / 1000;
int hours = (int) (seconds / 3600);
Or using the Joda-Time API's Period class, you can use the constructor public Period(long startInstant, long endInstant) and retrieve the hours field:
Period period = new Period(c1.getTimeInMillis(), c2.getTimeInMillis());
int hours = period.getHours();
In Java 8 you could do
long hours = ChronoUnit.HOURS.between(c1.toInstant(), c2.toInstant());
Related
From the below java code I'm getting a month First & last dateTimestamp, but here i need last dateTimestamp as - "Mon Aug 31 23:59:59 IST 2015" instead of - "Mon Aug 31 00:00:00 IST 2015"?
Calendar cal = Calendar.getInstance();
int year = 2015;
int month = 07;
cal.set(cal.DATE,1);
cal.set(cal.YEAR,year);
cal.set(cal.MONTH, month);
String firstDate = (cal.getActualMinimum(cal.DATE) + "/" + (month+1) + "/" +year);
System.out.println("firstDate-->"+"\t"+firstDate);
String lastDate = (cal.getActualMaximum(cal.DATE) + "/" + (month+1) + "/" +year);
System.out.println("lastDate-->"+"\t"+lastDate);
DateFormat firstFormat = new SimpleDateFormat("dd/MM/yyyy");
Date beginDate = firstFormat.parse(firstDate);
System.out.println("BeginDate Timestamp"+ "\t" + beginDate);
DateFormat secoundFormat = new SimpleDateFormat("dd/MM/yyyy");
Date endDate = secoundFormat.parse(lastDate);
System.out.println("endDate Timestamp"+ "\t" + endDate);
Output:->
firstDate--> 1/8/2015
lastDate--> 31/8/2015
BeginDate Timestamp Sat Aug 01 00:00:00 IST 2015
endDate Timestamp Mon Aug 31 00:00:00 IST 2015
Please help me if we have any solution.
If I understand your question, it looks as if you want to pass a year and month into a method, and get back the last day of the passed month.
I would suggest consider (in this order):
which jdk you use
configuration of calendar
configuration of timezone (maybe)
using jodatime
As of 1.8 many JodaTime-like features have been added to the jdk- e.g. see https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html (If you arent using 1.8 you can use the joda lib, assuming your organization allows it)
Calendar.getInstance() gives a default TimeZone and a default Locale, which means the definitions of the running JVM. You may or may not need to consider this and implement more than just getInstance(). See API javadoc.
Assuming a Gregeorian Calendar (hey, you could be Bahaian and have 19 months in the year ...) , here is one partial implementation using JDK 1.7, JodaTime jar 2.2, validation-1.0.0.GA jar:
#Test
public void testDate() {
final String dateStringOfFirstDay = "1.7.2015";
final Date lastDayOfMonth = getLastDayOfMonth(dateStringOfFirstDay);
Assert.assertNotNull(lastDayOfMonth);
//more assertions ...
}
private Date getLastDayOfMonth(#NotNull String dateStringOfFirstDay) {
//further validation here necessary according to required date format
DateTime dt = DateTime.parse(dateStringOfFirstDay);
return dt.dayOfMonth().withMaximumValue().toDate();
}
The defintion of DateFormat/DateTimeFormat and further result assertions is left up to you.
Best of luck!
Guys I got a solution for my question!!!
I think it will help u too...
Calendar calendar = Calendar.getInstance();
int year=2015;
int month=7;
int date=31;
int hourOfDay=23;
int minute=59;
int second=59;
int milliSecond=999;
calendar.set(year, month, date, hourOfDay, minute, second);
calendar.set(calendar.MILLISECOND, milliSecond);
System.out.println("Time from Calendar: "+calendar.getTime());
long timeInMilliSeconds=calendar.getTimeInMillis();
System.out.println("timeInMilliSeconds from calendar: "+timeInMilliSeconds);
Timestamp timestamp=new Timestamp(timeInMilliSeconds);
System.out.println(timestamp);
The above program gives the last date last timestamp in a selected month.
getTimeInMillis() takes the time from Jan 01, 1970 to current time in Milliseconds.
Using those milliseconds i'm getting the Timestamp.
Thank you for your help guys!!!
OutPut:->
Time from Calendar: Mon Aug 31 23:59:59 IST 2015
timeInMilliSeconds from calendar: 1441045799999
2015-08-31 23:59:59.999
I'm converting a specific datetime fromat by deducting -5 minutes from the current date I retrieve:
csvFileDate is a list of dates with format, yyyyMMddhhmm. Below is the code I'm using but its converting the date wrong:
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmm");
private List<String> csvFileDates = new ArrayList<String>();
....
Collections.sort(csvFileDates);
String currDate = csvFileDates.get(csvFileDates.size() -1);
System.out.println("DATE1 " + currDate);
Calendar c = Calendar.getInstance();
c.setTime(dateFormat.parse(currDate));
c.add(Calendar.MINUTE, -5);
System.out.println("DATE2 " + c.getTime());
output:
DATE1 201505181208
DATE2 Mon May 18 00:03:00 SGT 2015
Another:
DATE1 201505181213
DATE2 Mon May 18 00:08:00 SGT 2015
Any idea why?
You have 24 hours time format. So you have to use uppercase H for hours:
H Hour in day (0-23)
h Hour in am/pm (1-12)
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
See the documantation of SimpleDateFormat for more details.
Use HH instead of hh for hour of the day, as stated here
I have 2 dates in String with format (MMM dd, yyyy hh:mm:ss a).
How to convert two Strings into date and find the difference in minutes ?
DateFormat df = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a", Locale.ENGLISH);
Date start = df.parse(startstring);
Date end = df.parse(endstring);
After I want to take the difference in minutes and I am using this code:
long result = ((end.getTime()/60000) - (start.getTime()/60000));
But the result is 0. How can I solve this problem ?
My Strings are :
start: Fri Mar 07 23:45:43 GMT+04:00 2014
end: Fri Mar 07 23:46:01 GMT+04:00 2014
You could use this approach (first calculate the minutes since epoch, then subtract them) -
private static long getTimeInMinutesFromEpoch(Date d) {
if (d == null) {
return 0;
}
return d.getTime() / (60 * 1000);
}
public static long getMinuteDifference(Date a, Date b) {
return Math.abs(getTimeInMinutesFromEpoch(b)
- getTimeInMinutesFromEpoch(a));
}
public static void main(String[] args) throws ParseException {
String startstring = "Mar 07, 2014 23:45:43 PM";
String endstring = "Mar 07, 2014 23:46:01 PM";
DateFormat df = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a",
Locale.ENGLISH);
Date start = df.parse(endstring);
Date end = df.parse(startstring);
System.out.println(getMinuteDifference(start, end));
}
Output is
1
From the looks of it you're creating the start date immediately before the end date (unless there is non-included relevant information).
Date start = df.parse(startstring);
Date end = df.parse(endstring);
These are going to be created in exactly the same minute and therefore give you 0 when you try to find the difference in minutes.
EDIT
Your times:
start: Fri Mar 07 23:45:43 GMT+04:00 2014
end: Fri Mar 07 23:46:01 GMT+04:00 2014
are 18 seconds apart. You're going to get 0 for the difference in minutes.
You can make Calendar object instead of Date and then you can get the minutes using Calendar.get(Calendar.MINUTE). Note that by using this logic, the difference between 22:45:43 GMT+04:00 2014 and 23:45:43 GMT+04:00 2014 will be zero minutes.
If we have 2 dates
Previous Date : Wed Jun 02 17:30:00 CDT 2010
Next Date : Sun Feb 13 22:00:00 CST 2011
and need to find difference in mins. between these 2 dates
Is there a way to accurately get it?
Yes, you can get an accurate difference of those times:
Parse each one with SimpleDateFormat to get a Date.
Get the time in milliseconds since the Epoch from each.
Subtract the two times and divide by 60000 for minutes.
Here's the code:
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
Date prevDate = sdf.parse("Wed Jun 02 17:30:00 CDT 2010");
Date nextDate = sdf.parse("Sun Feb 13 22:00:00 CST 2011");
long diffTime = nextDate.getTime() - prevDate.getTime();
System.out.println(diffTime / 60000 + " minutes");
date1.getTime() - date2.getTime() will give you the difference in milliseconds. You can then divide it by 60000 to get the difference in minutes.
Use TimeUnit class for convertion.
// specify the input format
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
String s1 = "Wed Jun 02 17:30:00 CDT 2010";
String s2 = "Sun Feb 13 22:00:00 CST 2011";
// parse to Date object
Date d1 = dateFormat.parse(s1);
Date d2 = dateFormat.parse(s2);
// get time in milliseconds
long l1 = d1.getTime();
long l2 = d2.getTime();
// absolute difference
long diff = Math.abs(l1 - l2);
// convert milliseconds to minute
long min = TimeUnit.MILLISECONDS.toMinutes(diff);
System.out.println(min);
With Joda Time
DurationFormatUtils.formatDuration(date2.getTime() - date1.getTime(), "m");
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
How to determine the date one day prior to a given date in Java?
If I have a Java.Util.Date object, what is the best way to get an object representing the 24 hours in the past of it?
Using Java 1.6 java.util.Calendar.add:
public static Date subtractDay(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, -1);
return cal.getTime();
}
Others suggest using Joda Time, which is currently JSR 310, and should later be included in Java itself.
The important thing to remember is that the Date class should represent any points in time whilst the Calendar class is used to manipulate those points in time. Last of all, SimpleDateFormat will represent them as Strings.
So, the best way is to use the Calendar class to calculate the new Date for you. This will ensure that any vagaries (Daylight Saving, Leap Years and the like) are accounted for.
I'm assuming that you don't really want to find '24 Hours previous' but actually do want a new Date instance representing 'this time yesterday' - either way, you can ask the Calendar instance for a Date 24Hours prior to another or 1 Day prior.
The Daylight savings is a great example. The UK 'sprang forward' on the 26th March 2009. So, 1 day prior to 3.00a.m. on the 26.Mar.2009 should yield 3.00a.m. 25.Mar.2009 but 24 Hrs prior will yield 2.00a.m.
public class DateTests extends TestCase {
private static String EXPECTED_SUMMER_TIME = "2009.Mar.29 03:00:00";
private static String EXPECTED_SUMMER_TIME_LESS_DAY = "2009.Mar.28 03:00:00";
private static String EXPECTED_SUMMER_TIME_LESS_24_HRS = "2009.Mar.28 02:00:00";
private static String EXPECTED_SUMMER_TIME_LESS_FURTHER_24_HRS = "2009.Mar.27 02:00:00";
public void testSubtractDayOr24Hours() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MMM.dd HH:mm:SS");
Calendar calendar = Calendar.getInstance();
// Create our reference date, 3.00 a.m. on the day the clocks go forward (they 'went' forward at 02.00)
calendar.clear();
calendar.set(2009, 2, 29, 3, 0);
Date summerTime = calendar.getTime(); // Sun Mar 29 03:00:00 BST 2009
String formattedSummerTime = formatter.format(summerTime);
calendar.add(Calendar.DAY_OF_MONTH, -1);
// Our reference date less 'a day'
Date summerTimeLessADay = calendar.getTime(); // Sat Mar 28 03:00:00 GMT 2009
String formattedSummerTimeLessADay = formatter.format(summerTimeLessADay);
// reset the calendar instance to the reference day
calendar.setTime(summerTime);
// Our reference date less '24 hours' (is not quite 24 hours)
calendar.add(Calendar.HOUR, -24);
Date summerTimeLess24Hrs = calendar.getTime(); // Sat Mar 28 02:00:00 GMT 2009
String formattedSummerTimeLess24Hrs = formatter.format(summerTimeLess24Hrs);
// Third date shows that taking a further 24 hours from yields expected result
calendar.add(Calendar.HOUR, -24);
Date summerTimeLessFurther24Hrs = calendar.getTime(); // Fri Mar 27 02:00:00 GMT 2009
String formattedSummerTimeLessFurther24Hrs = formatter.format(summerTimeLessFurther24Hrs);
// reset the calendar once more to the day before
calendar.setTime(summerTimeLess24Hrs);
// Take a 'day' from the Sat will yield the same result as date 03 because Daylight Saving is not a factor
calendar.add(Calendar.DAY_OF_MONTH, -1);
Date summerTimeLessFurtherDay = calendar.getTime(); // Fri Mar 27 02:00:00 GMT 2009
String formattedSummerTimeLessFurtherDay = formatter.format(summerTimeLessFurtherDay);
assert(formattedSummerTime.equals(EXPECTED_SUMMER_TIME));
assert(formattedSummerTimeLessADay.equals(EXPECTED_SUMMER_TIME_LESS_DAY));
assert(formattedSummerTimeLess24Hrs.equals(EXPECTED_SUMMER_TIME_LESS_24_HRS));
assert(formattedSummerTimeLessFurther24Hrs.equals(EXPECTED_SUMMER_TIME_LESS_FURTHER_24_HRS));
// This last test proves that taking 24 hors vs. A Day usually yields the same result
assert(formattedSummerTimeLessFurther24Hrs.equals(formattedSummerTimeLessFurtherDay));
}
}
For testing date functions, wwwdot-timeanddate-dot-com is a great resource.
subtract 1000*60*60*24 from the time and create a new date.
Date yesterday = new Date(d.getTime() - (1000*60*60*24));
int dayInMs = 1000 * 60 * 60 * 24;
Date previousDay = new Date(olddate.getTime() - dayInMs);
Personally if there are a lot of time/date calculations, I'd go with Joda-time.