Search code examples
javadatetimerelative-time-span

How do I get input of multiple values using Java?


Using Vincent Robert's answer, I want to rebuild it in Java.

I started off this way:

// This is a draft of the program.

import java.time.LocalDateTime;
import java.util.Scanner;
import java.lang.*;

public class Test
{
    public String calcRelTime(int past_month, int past_day, int past_year)
    {
        // initialization of time values
        int minute = 60;
        int hour = 60 * minute;
        int day = 24 * hour;
        int week = 7 * day;
        int month = (365.25 * day) / 12;
        int year = 12 * month;
        // main part of function
        LocalDateTime present = LocalDateTime.now();
        /*
            Something similar to:
            var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);
            double delta = Math.Abs(ts.TotalSeconds);
        */
        // the if-condition statement similar to the answer, but I won't write it down here as it is too much code
    }
    public static void main(String[] args)
    {
        Scanner input;
        int mon, day, year;
        System.out.println("Enter date: ");
        // the line where I take input of the date from the user
        System.out.println("That was " + calcRelTime(mon, day, year) + ", fellow user.");
    }
}

Now in the main() function, I want to do something similar from C's scanf("%d/%d/%d", &mon, &day, &year);. How can I implement something like that in Java using a single line?

I'm expecting this kind of input:

8/24/1995 12:30PM
%d/%d/%d %d/%d%cM

Solution

  • Using the modern date-time API and String#format, you can do it as follows:

    import java.time.Duration;
    import java.time.LocalDateTime;
    import java.time.Period;
    import java.time.format.DateTimeFormatter;
    import java.time.format.DateTimeFormatterBuilder;
    import java.time.temporal.ChronoField;
    import java.util.Locale;
    import java.util.Scanner;
    
    class Main {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            System.out.print("Enter date-time in the format MM/dd/yyyy hh:mm:ssa e.g. 8/24/1995 12:30PM: ");
            String dateTime = input.nextLine();
            System.out.println(calcRelTime(dateTime));
        }
    
        static String calcRelTime(String dateTimeString) {
            LocalDateTime now = LocalDateTime.now();
    
            DateTimeFormatter formatter = new DateTimeFormatterBuilder().parseCaseInsensitive() // Case insensitive e.g. am,
                                                                                                // AM, Am etc.
                    .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0) // Default second to 0 if absent
                    .appendPattern("M/d/u h:m[ ]a") // Optional space before AM/PM
                    .toFormatter(Locale.ENGLISH);
    
            LocalDateTime ldt = LocalDateTime.parse(dateTimeString, formatter);
    
            Duration duration = Duration.between(ldt, now);
    
            Period period = Period.between(ldt.toLocalDate(), now.toLocalDate());
    
            return String.format("%d years %d months %d days %d hours %d minutes %d seconds", period.getYears(),
                    period.getMonths(), period.getDays(), duration.toHoursPart(), duration.toMinutesPart(),
                    duration.toSecondsPart());
        }
    }
    

    A sample run:

    Enter date-time in the format MM/dd/yyyy hh:mm:ssa e.g. 8/24/1995 12:30PM: 8/24/1995 12:30PM
    25 years 3 months 14 days 7 hours 37 minutes 39 seconds
    

    Learn more about the modern date-time API at Trail: Date Time.