-2

I would like to know how I can tell to this simple program to replace the "2016-yearOfBirth" string with a "computer time - yearOfBirth".

I don't know how to set the computer time as an int and how to proceed...

public static void main(String[] args) {
    Scanner in;
    int yearOfBirth, years;
    in = new Scanner (System.in);
    System.out.print ("Year of Birth: ");
    yearOfBirth = in.nextInt();
    years = 2016 - yearOfBirth;
    System.out.println("You are almost "+years+" years old");
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 1
    Possible duplicate of [How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"](http://stackoverflow.com/questions/23068676/how-to-get-current-timestamp-in-string-format-in-java-yyyy-mm-dd-hh-mm-ss) – OneCricketeer Oct 15 '16 at 18:05
  • I think that's what you are asking... Of course, you just want `yyyy` format, it looks like – OneCricketeer Oct 15 '16 at 18:06
  • Or [Java - Get Current year](http://stackoverflow.com/questions/2891645/java-how-to-get-current-year) – OneCricketeer Oct 15 '16 at 18:07
  • @cricket_007 No, sorry if I created any misunderstanding but I'm new here and I'm still trying to understand how this works. By the way I needed the string posted by the user down here...but thank you anyway for your help! –  Oct 15 '16 at 18:20

2 Answers2

0
years = Calendar.getInstance().get(Calendar.YEAR) - yearOfBirth;
Filipp Voronov
  • 4,077
  • 5
  • 25
  • 32
  • 1
    FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Feb 03 '19 at 19:06
0

tl;dr

Use the modern java.time classes.

long age = 
    ChronoUnit.YEARS.between( 
        LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ,
        LocalDate.now( ZoneId.of( "Pacific/Auckland" ) )
    )
;

See this code run live at IdeOne.com.

age: 32

java.time

The modern approach uses java.time classes that supplanted the terrible date-time classes bundled with the earliest versions of Java.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.

LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.

Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety. Ditto for Year & YearMonth.

LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;

Elapsed years

To determine age, use date-time math. For just a number of years, without months-days, use ChronoUnit.

LocalDate then = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
LocalDate now = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ;
long age = java.time.temporal.ChronoUnit.YEARS.between( then , now  ) ;

age: 32

For years-months-days, use Period class.

Period p = Period.between( then , now ) ;

p.toString(): P32Y11M11D

You can interrogate the Period for the number of years.

int years = p.getYears() ;

years: 32


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154