简体   繁体   中英

finding age in months, weeks, or days

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)
{
    ///?
}

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 ...

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()));
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM