0

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

3 Answers3

0

One Possible approach is :

public static void main(String[] args)
 {
    Scanner input;
    int mon=Integer.parseInt(args[0]), day=Integer.parseInt(args[1]), 
    year=Integer.parseInt(args[2]);
    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.");
 }

Making use of String []args 

while running from CMD : use command 



  java Test 1 28 2020



   Example :
    mon=1 
    day=28
    year=2020
  • Not exactly what I was looking for. You could've filled in that comment, that's what I'm hoping to be dealt with. –  Dec 08 '20 at 19:19
0

This works, albeit you need to add another / character after the year.

Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("/");
System.out.print("Enter date [dd/mm/yyyy/]: ");
int day = scanner.nextInt();
int month = scanner.nextInt();
int year = scanner.nextInt();
scanner.nextLine();
System.out.println("day = " + day);
System.out.println("month = " + month);
System.out.println("year = " + year);
scanner.useDelimiter(":|\\s");
System.out.println("Enter time [HH:mm am]: ");
int hour = scanner.nextInt();
int min = scanner.nextInt();
String apm = scanner.next();
System.out.println("hour = " + hour);
System.out.println("minute = " + min);
System.out.println(apm);

For example:

Enter date [dd/mm/yyyy/]: 12/11/1997/
day = 12
month = 11
year = 1997
Enter time [HH:mm am]: 
04:50 pm
hour = 4
minute = 50
pm

Nonetheless, Java is not C (and C is not Java). Trying to code in Java exactly the same way as you do in C is like writing Arabic from left to right. In Java just use method nextLine() to read an entire line of input it and then parse that input.

System.out.print("Enter date [dd/mm/yyyy]: ");
String input = scanner.nextLine();
String[] parts = line.split("/");
int day = Integer.parseInt(parts[0]);
int month = Integer.parseInt(parts[1]);
int year = Integer.parseInt(parts[2]);
Abra
  • 19,142
  • 7
  • 29
  • 41
  • It's a cool answer, to be honest. How can I do the same thing with the time value (like **3:34 PM**)? –  Dec 08 '20 at 19:34
  • @MarkGiraffe the parameter to method [useDelimiter](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#useDelimiter-java.lang.String-) is a regular expression. You can set the delimiter to be either `:` or a single space. – Abra Dec 08 '20 at 19:37
  • So what you're saying is to call the function in a certain time I have to change the delimeter of the value? –  Dec 08 '20 at 19:39
0

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110