Reputation: 1800
I have a little java code that finds the date of a person. It looks like this:
Calendar now = Calendar.getInstance();
Calendar dob = Calendar.getInstance();
dob.setTime(birthDay); /*assume this is not null */
int age = now.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (now.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR))
{
age--;
}
Now, I want to say if the person is less than 1 year old, find how many months this person is. If the person is less than 1 month old, find how many weeks this person is. and if this person is less than 1 week old, find out how many days this person is.
psuedo code:
if (age < 1)
{
///?
}
Upvotes: 0
Views: 1640
Reputation: 1841
Something like:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class TimeDiff {
public static void main(String[] args) throws ParseException {
Date now = new Date();
System.out.println(now);
Date birthDate = new SimpleDateFormat("dd-MM-yyyy").parse("7-12-1983");
System.out.println(birthDate);
Date age = new Date(now.getTime() - birthDate.getTime());
Calendar instance = Calendar.getInstance();
instance.setTime(age);
instance.add(Calendar.YEAR, -1970);
SimpleDateFormat sdf = new SimpleDateFormat("d-W-MM-yyyy");
System.out.println(sdf.format(instance.getTime()));
}
}
Upvotes: 1
Reputation: 3827
getTimeInMillis()
gives you the time in milliseconds. With that value, you can simply calculate. How many milliseconds are in a second, how many in a minute, an hour, a day, a month and so on.
Time in seconds: var a = milliseconds / 1000. Time in minutes: a / 60 ...
Upvotes: 1