Home > Blockchain >  Calculate the user age with LocalDateTime
Calculate the user age with LocalDateTime

Time:12-30

I'm trying to make a program which prompts the user for the year of their birthday (like 2001). And then do some mathematical things (present time - the year that user write like (2021 - 2001)). However, I get this error:

Operator "-" cannot be applied to string int.

How to fix this error?

The code:

package com.myApp.User;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;

public class GetUserAge {

    public String localtimeYear;
    public int userBirthdayYear;

    public static void main(String[] args) {

        Scanner scannerObject = new Scanner(System.in);
        GetUserAge getUserAgeObject = new GetUserAge();
        LocalDateTime localDateObject = LocalDateTime.now();
        DateTimeFormatter localDateObjectFormatted = DateTimeFormatter.ofPattern("yyyy");

        getUserAgeObject.localtimeYear = localDateObject.format(localDateObjectFormatted);
        // System.out.println(getUserAgeObject.localtimeYear); => 2021
        getUserAgeObject.userBirthdayYear = scannerObject.nextInt();
       System.out.println(calculateTrueBirthdayYear(getUserAgeObject.userBirthdayYear));
    }

    static int calculateTrueBirthdayYear(int userBirthdayYear) {

        GetUserAge getUserAgeObject = new GetUserAge();

        return (getUserAgeObject.localtimeYear - userBirthdayYear);
    }
}

CodePudding user response:

String is not numeric

Your error must be coming from this line:

return (getUserAgeObject.localtimeYear - userBirthdayYear);

… because the member field localtimeYear refers to a String object. You cannot use the numeric operator - on a String object.

Year class

If you want to focus on year only, use Year class.

Year currentYear = Year.now() ;
Year birthYear = Year.of( 1970 ) ;

Do the math.

int approximateYearsOld = currentYear.getValue() - birthYear.getValue() ;

Example class.

package work.basil.age;

import java.time.Year;

public record Person( String name , Year birth )
{
    public int calculateApproximateAge ( )
    {
        return ( Year.now().getValue() - this.birth.getValue() );
    }
}

Usage.

Person alice = new Person( "Alice" , Year.of( 1972 ) );
int approxAge = alice.calculateApproximateAge();

System.out.println( "alice = "   alice );
System.out.println( "approxAge = "   approxAge );

alice = Person[name=Alice, birth=1972]

approxAge = 49

CodePudding user response:

Why not make use of the available API you could do something like...

LocalDate ld = LocalDate.of(1972, Month.MARCH, 8);
Period p = Period.between(ld, LocalDate.now());
System.out.println(p.getYears());
System.out.println(p.getMonths());
System.out.println(p.getDays());
  • Related