This question already has answers here:
How can I find the number of days between two Dates?
(5 answers)
Closed 6 years ago.
Problem: Getting the difference in calendar days between two dates. For an example, 6/28/1996 23:59 is one day difference from 6/29/1996 12:00.
Research: I did a bunch of research online and everyone seems to only give the difference in milliseconds, which gives you the true difference in times, but not in calendar days.
Current Solution
(int) ((new java.sql.Date(System.currentTimeMillis()).getTime()/day_conversion)) - (int) (rs.getDate("attempt_time").getTime()/day_conversion) > 0
I did an int cast to the time of the date converted to days (thereby dropping any decimals) to both the current time and recorded time and took the difference. This left me with the actual conversion in calendar days; however, I was wondering if there is just a single written method that does this for me already.
Since Java 8 there exists the java.time API, superseding java.util.Date and related classes and providing a very clean way of solving your problem:
LocalDateTime date1 = LocalDateTime.of(1996, 6, 28, 23, 59);
LocalDateTime date2 = LocalDateTime.of(1996, 6, 29, 12, 59);
Period difference = Period.between(date1.toLocalDate(), date2.toLocalDate());
System.out.println(difference.getDays());
This is another way to compute difference between years. You can add the rest of date very easily.
Calendar c = Calendar.getInstance();
int y = c.get(Calendar.YEAR);
Calendar c2 = Calendar.getInstance();
c2.set(Calendar.YEAR, 2013);
int com = c.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
System.out.println(com);
Related
This question already has answers here:
WHERE datetime older than some time (eg. 15 minutes)
(2 answers)
Adding/Subtracting 5 seconds from Java Date - Showing deprected warning
(9 answers)
Changing Java Date one hour back
(11 answers)
Closed 2 years ago.
I need to delete some records from the database. In the table, I have a column with Date (java.util.Date) records. I need to get from the table the rows that are older than x hours for example. My function has an int Y that deserves seconds. I need to make something like that. Date (currentDate) - Y. And after that to make a query where I compare that column with the calculation. Any suggestion?
First, if you work with java 8 or higher I would strongly advise not to use outdated class java.util.Date and switch to package java.time. You can use class ZonedDateTime or any of its "brothers" such as LocalDateTime or others.
But, to answer your question here is how you can substruct seconds from Date class:
Date date = new Date(); //Current date
long seconds = 100L; // 100 seconds to substruct
date.setTime(date.getTime() - seconds * 1000); //convert seconds to milliseconds and substruct it from current value of date
I solved this with this function. I hope will be helpful for somebody.
private Date calculateTheDate(final int seconds){
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, - seconds);
return calendar.getTime();
}
This question already has answers here:
Unix epoch time to Java Date object
(7 answers)
Closed 4 years ago.
I am trying to get a date, time and day from open weather API of a specific location and specific day using latitude and longitude. But it gives me a long integer something like this 1525974999. How can I retrieve date time and day from this?
Using Java 8 Time API:
Instant.ofEpochSecond(1525974999) // returns: 2018-05-10T17:56:39Z
Using old Java Date:
new Date(1525974999 * 1000L) // returns: Thu May 10 13:56:39 EDT 2018
I'm in Eastern US time zone
The integer represents the amount of time it has been passed since January, 1, 1970. (Unix Time Stamp)
You can use a converter from unix time stamp or just do the math programmatically.
It's probably in seconds. Try this:
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timeReturnedByAPI * 1000);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
Here is the Calendar API: https://developer.android.com/reference/java/util/Calendar
Edit: You may want to use the version of getInstance that takes a time zone to get the local time.
Edit 2: Updated in response to comments.
This question already has answers here:
Calendar returns wrong month [duplicate]
(9 answers)
Closed 5 years ago.
Something strange happens when I am trying to convert date to a milliseconds. Maybe someone can explain my this:
Calendar calendar = Calendar.getInstance();
calendar.set(2017, 9, 3, 4, 50);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss",
Locale.getDefault());
Log.i("tag", formatter.format(calendar.getTime()));
and logcat logs my out:
I/tag: 2017.10.03 04:50:34
Why months are different ?
Calendar month is zero-based (0-11) but when displayed it's in "human" version (1-12).
In the method calendar.set(), from the documentation the parameter month starts from 0.
month the value used to set the MONTH calendar field.
* Month value is 0-based. e.g., 0 for January.
This question already has answers here:
Why is January month 0 in Java Calendar?
(18 answers)
Closed 9 years ago.
I would like to understand why this happens, and how can i solve this small issue.
I would like to be able to get the week number from a java calendar instance after providing the day, the month and the year.
if i do:
Calendar cal=Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 11);
cal.set(Calendar.MONTH,2);
cal.set(Calendar.YEAR, 2013);
11 Feb 2013 is week 7, but if i invoke, in the above calendar instance:
int weekNumber=cal.get(Calendar.week_of_year)
I get the week number 11.
Any idea why?
I tried setting the locale but no difference, the problem is that i can only build a calendar out of these three fields, since i'm reading them from a xml file with a parser and they are in format dd-mm-yyyy with no more information that that
Months fields in Calendar are zero based. The value 2 corresponds to Calendar.MARCH. To avoid confusion, better to use the Calendar constants. You could use:
cal.set(Calendar.MONTH, Calendar.FEBRUARY);
You have used March, because Java months in Calendar are 0-based: 0 = January, 1 = February, 2 = March.
Use
cal.set(Calendar.MONTH,1);
or
cal.set(Calendar.MONTH, Calendar.FEBRUARY);
if you can use a constant. Else, subtract 1 from the month you received from your parser.
This question already has answers here:
How to create a Date object, using UTC, at a specific time in the past?
(2 answers)
Closed 5 years ago.
How can I return a Date object of 4 hours less than the current system time in Java?
If you're already on Java 8 or newer:
LocalDateTime fourHoursAgo = LocalDateTime.now().minusHours(4);
Or if you want to take DST (Daylight Saving Time) into account (just in case it coincidentally went into or out DST somewhere the last 4 hours):
ZonedDateTime fourHoursAgo = ZonedDateTime.now().minusHours(4);
Or if you're not on Java 8 yet:
Date fourHoursAgo = new Date(System.currentTimeMillis() - (4 * 60 * 60 * 1000));
And you want to take DST into account:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR_OF_DAY, -4);
Date fourHoursAgo = calendar.getTime();
The other answers are correct, but I would like to contribute the modern answer. The modern solution uses java.time, the modern Java date and time API.
Instant fourHoursAgo = Instant.now().minus(Duration.ofHours(4));
System.out.println(fourHoursAgo);
This just printed:
2018-01-31T15:22:21.113710Z
The Z in the end indicates that the time is printed in UTC — at UTC offset zero if you will. The Instant class is the modern replacement for Date, so I recommend you stick to it. The modern API is generally so much nicer to work with, so much cleaner, so much better designed.
Please note the advantages of letting the library class do the subtraction of 4 hours for you: the code is clearer to read and less error-prone. No funny constants, and no readers taking time to check if they are correct.
If you do need an old-fashioned Date object, for example when using a legacy API that you cannot change or don’t want to change, convert like this:
Date oldfashionedDate = Date.from(fourHoursAgo);
Link: Oracle Tutorial trail: Date Time. Of course there are other resources on the internet too, please search.
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR_OF_DAY, -4);
calendar.getTime();
Convert it to milliseconds, subtract the number of milliseconds in 4 hours, convert it back to a Date.
Calendar c = Calendar.getInstance();
c.add(Calendar.HOUR_OF_DAY, -4);
java.util.Date d = c.getTime();
System.out.println(d);
Calendar c =Calendar.getInstance() ;
c.add(Calendar.HOUR,-4);
Date d = c.getTime();
Use a Calendar object and the add method.
calendar.add(Calendar.HOUR, -4);
See http://download.oracle.com/javase/6/docs/api/java/util/Calendar.html