-5

I'm attempting to write a program where I can insert a string such as

5d2h7m (5 days 2 hours 7 minutes)

and it will take

System.currentTimeMillis();

and add the 5 days 2 hours and 7 minutes to get a new value, which I then save. Later when needed I can check the saved time to see if it has passed.

I'm confused on how to convert 5 days 2 hours and 7 minutes into milliseconds.

Is there a generic Java method for this that I'm missing?

Edit: I'm trying to convert the string into milliseconds, not the other way around.

Jordan Osterberg
  • 289
  • 3
  • 18
  • 2
    you have to post code to get help, posting requirements and showing no attempt/effort is just asking others to do your work for free. –  Jul 07 '16 at 17:38
  • You can use the new [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) package for this. Look at Duration and Period. – ManoDestra Jul 07 '16 at 17:39
  • Then just do the opposite of the duplicate, it is that simple, you have to show some effort to get help with existing code. –  Jul 07 '16 at 17:39

2 Answers2

1

Here's what I did to solve my problem: (timeArgs is a String[] that was split up from the string in the problem)

        long days = 0;
        long hours = 0;
        long minutes = 0;

            for (int x = 0; x < timeArgs.length; x++) {
                if (timeArgs[x].contains("d")) {
                    days = Long.parseLong(timeArgs[x].replace("d", ""));
                    break;
                } else if (timeArgs[x].contains("h")) {
                    hours = Long.parseLong(timeArgs[x].replace("h", ""));
                    break;
                } else if (timeArgs[x].contains("m")) {
                    minutes = Long.parseLong(timeArgs[x].replace("m", ""));
                    break;
                }
            }

        long millis = System.currentTimeMillis() + TimeUnit.DAYS.toMillis(days) + TimeUnit.HOURS.toMillis(hours) + TimeUnit.MINUTES.toMillis(minutes); // Current time plus other values
        System.out.print("millis is " + millis);
Jordan Osterberg
  • 289
  • 3
  • 18
  • *"timeArgs is a String[] that was split up from the string in the problem"* How? Show that part. Also, remove unnecessary indentation. Congrats on your first answer! – T.J. Crowder Jul 07 '16 at 17:58
  • Probably worth mentioning: The use of `TimeUnit` is a convenience. In reality, the number of milliseconds in a day is variable (DST, leap seconds), but as used above it's a constant: `1000L * 60 * 60 * 24`. And the same for the others. Still, `TimeUnit` is there, and reusing it avoids embarrassing bugs like missing out one of the `* 60` or some such. – T.J. Crowder Jul 07 '16 at 18:00
0

Is there a generic Java method for this that I'm missing?

No, not in the JDK. You have to parse the string yourself, probably using java.util.regex, then do the appropriate multiplication and addition yourself.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875