This question already has answers here:
How do I calculate someone's age in Java?
(28 answers)
Closed 8 years ago.
I have an Problem with calculating an Age..
public long getAlter() {
Date now = new Date();
long yearInMillis = 365 * 24 * 60 * 60 * 1000;
long alter = (now.getTime() - buildYear.getTime()) /365/24/60/60/1000 ;
return alter;
}
The buildYear is given: Year 22.05.2007.
--> (dd.mm.yyyy)
I need a function to calculate the Year (not the Month or so), in this example here: 7 Years.
I need a function to calculate the Days, in this example 2576 Days.
How can I define this?
Like this:
http://www.topster.de/kalender/zeitrechner.php?styp=zeit&sdatum=22.05.2007&szeit=12%3A00%3A00&edatum=&ezeit=12%3A00%3A00&typ=jetzt&subDazu=%2B&jahredazu=0&tagedazu=0&zeitdazu=00%3A00%3A00
(already choosen)
#ALL: It's not an duplicate, because I will not work with Joda!
This link seems to have done something similar:
How do I calculate someone's age in Java?
In case the link ever breaks, here is what is said:
Check out Joda, which simplifies date/time calculations (Joda is also
the basis of the new standard Java date/time apis, so you'll be
learning a soon-to-be-standard API).
EDIT: Java 8 will have something very similar and will be worth
checking out.
e.g.
LocalDate birthdate = new LocalDate (1970, 1, 20);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);
which is
as simple as you could want. The current Java stuff is (as you've
identified) somewhat unintuitive.
Related
This question already has answers here:
Java Date month difference
(22 answers)
Closed 1 year ago.
In a tutorial I am watching,I am trying to calculate the difference between two dates. I need the initMonth and the finishMonth with the idea being to subtract the initMonth from the finishMonth and calculate the difference.
I can do something like this using the Calendar class(and then something similar with the finishMonth):
int initMonth = calendar.get(Calendar.MONTH);
...but the problem is that if the initMonth is May(for example) and the endMonth is January; when I subtract the endMonth from the initMonth I will get 1-5=-4--and I will have a negative difference. In order to solve this problem, the instructor came with the solution of multiplying the YEAR * 12 and then adding the month like this:
int initMonth = calendar.get(Calendar.YEAR) *12 + calendar.get(Calendar.MONTH);
However, this doesn't make any sense to me since the year will return something like 2021 * 12 + month to some extremely large number. My guess was that he meant MONTH so then we will get the months in the year plus the month. Would I be correct? I'm unsure, and wanted to confirm this logic.
Thank you in advance.
Your tutorial is obsolete by several years. Never use Calendar or Date class. Use only java.time classes.
Apparently you want to calculate elapsed months.
LocalDate then = LocalDate.of( 2020 , Month.MARCH ) ;
LocalDate today = LocalDate.now() ;
Period elapsed = Period.between ( then , today ) ;
int months = elapsed.toMonths() ;
Search Stack Overflow to learn more. This has been covered many times already.
This question already has answers here:
Why is this not casting to long
(1 answer)
How to subtract X day from a Date object in Java?
(10 answers)
Closed 4 years ago.
I need to subtract several months of time from a java.util.Date object to get a different java.util.Date. I know that there is a simple way to do this in java 8, however this must be run on my school's server that does not support java 8. My current solution looks like this:
int numDaysToSubtract = 60;
Date curDate = new Date();
//subtract numdays * hours/day * mins/hour * secs/min * millisecs/sec
Date newDate = new Date(curDate.getTime() - (numDaysToSubtract * 24 * 3600 * 1000));
curDate is 4/12/2018 and the calculated newDate is 4/2/2018, which is clearly not 60 days before 4/12/2018.
Why isn't this working as expected?
What should I try instead?
You have overflowed the number of milliseconds to subtract, because the product doesn't fit in a 32-bit integer, whose maximum value is about 2.1 billion (10 digits).
60 days worth of milliseconds is 5,184,000,000, over the limit. Because of the overflow, the product is calculated at 889,032,704 milliseconds, or about 10.2 days.
Either cast numDaysToSubtract as a long, or declare it to be long to begin with, to force long calculations, avoiding overflow. For me, doing that results in February 11, 2018, 60 days ago.
This question already has answers here:
Do we have a TimeSpan sort of class in Java
(4 answers)
Closed 6 years ago.
I am trying to convert the following code which is in c# to java. And I am facing difficulty in converting it. Please can anyone suggest me a simple way to do it in Java.
DateTime StartDate = new DateTime(PWUpdatedOn.Year, 01, 01);
TimeSpan ts = new TimeSpan(PWUpdatedOn.Ticks - StartDate.Ticks);
//Response.Write(ts.Days+1);
days = ts.Days + 1;
lngN = 0;
PWUpdatedOn.Year = 2016 // current year
As Jigar Joshi answered in an other Question.
Interval from JodaTime will do..
A time interval represents a period of time between two instants. Intervals >are inclusive of the start instant and exclusive of the end. The end instant is always greater than or equal to the start instant.
Intervals have a fixed millisecond duration. This is the difference between the start and end instants.
The duration is represented separately by ReadableDuration. As a result, intervals are not comparable. To compare the length of two intervals, you should compare their durations.
An interval can also be converted to a ReadablePeriod. This represents the difference between the start and end points in terms of fields such as years and days.
Interval is thread-safe and immutable.
I am not sure what Ticks are in C#. But it would be something like:
LocalDateTime startDate = LocalDateTime.of(PWUpdatedOn.getYear(), 1, 1);
Period ts = Period.between(PWUpdatedOn, startDate.toLocalDate());
days = ts.getDays() + 1;
Note that Period.between() requires two LocalDate instances. If PWUpdateOn is a LocalDateTime instance, it needs to be converted with the method toLocalDate().
Some potentially relevant remarks: for zoned datetimes, use ZonedDateTime rather than LocalDateTimel; all time and period objects are immutable in Java.
This question already has answers here:
How do I calculate someone's age in Java?
(28 answers)
Closed 6 years ago.
I have 2 Calendar objects for the current date and birthdate.
I need to subtract birthdate from the current date and return the difference in years (a truncated Int is all I need).
What's the simplest way of doing this?
You can get EPOCH time (miliseconds since 01.01.1900), subtract both values and divide it by 1000(miliseconds)/60(seconds)/60(minutes)/24(hours)/365(days).
This would give you approximate result (in years) because of ignoring leap years.
To get epoch time, use Date#getTime();
This question already has answers here:
Get the weeknumber from a given date in Java FX
(4 answers)
Closed 8 years ago.
I'm trying to get the Week Number of a full LocalDate with the format:
dd.MM.yyy
I haven't found a function in the Java 8 Date API wich returns the Week Number and i have tried to create a algorithm, but it did'nt work.
One small warning. I haven't tested this yet, but looking at the API documentation of WeekFields and LocalDate.get, you should do something like:
LocalDate date = ...;
// Or use a specific locale, or configure your own rules
WeekFields weekFields = WeekFields.of(Locale.getDefault());
int weekNumber = date.get(weekFields.weekOfWeekBasedYear());
The answer of Mark Rotteveel is almost right and again an example which kind of confusion potential there is in the class WeekFields (similar sounding method names, but deviating from intuitive civil usage). The right code requires another field:
LocalDate date = LocalDate.now();
TemporalField woy = WeekFields.of(Locale.getDefault()).weekOfWeekBasedYear();
int weekNumber = date.get(woy);
See also the similar debate on this SO-post, especially the discussion and comments about the answer of #kleopatra.