Java Second Get getTimeSeconds(String time)

Here you can find the source of getTimeSeconds(String time)

Description

get Time Seconds

License

Apache License

Parameter

Parameter Description
string a parameter

Declaration

public static int getTimeSeconds(String time) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/*  w  w w  . j a v  a  2s .  c  om*/
     * @param string
     * @return
     */
    public static int getTimeSeconds(String time) {
        long mili = getTimeMillis(time);
        return Math.round(mili / 1000);
    }

    /**
     * Transforms the string into a millisecond timestamp<br/>
     * - Days in d, day or days<br/>
     * - Hours in h, hour or hours<br/>
     * - Minutes in m, minute or minutes<br/>
     * - Seconds in s, second or seconds<br/>
     * <br/>
     * returns -1 if the time cannot be transformed
     * @param time The string form of this time
     * @return the time in millis
     * @throws NumberFormatException when a numer cannot be parsed.
     */
    public static long getTimeMillis(String time) {
        long date = 0;
        String[] splits = time.split(" ");
        try {
            for (String s : splits) {
                if (s.length() > 1 && (s.endsWith("d") || s.endsWith("day") || s.endsWith("days"))) {
                    date += Integer.parseInt(s.substring(0, s.length() - 1)) * 24 * 60 * 60 * 1000;
                } else if (s.length() > 1 && (s.endsWith("h") || s.endsWith("hour") || s.endsWith("hours"))) {
                    date += Integer.parseInt(s.substring(0, s.length() - 1)) * 60 * 60 * 1000;
                } else if (s.length() > 1 && (s.endsWith("m") || s.endsWith("minute") || s.endsWith("minutes"))) {
                    date += Integer.parseInt(s.substring(0, s.length() - 1)) * 60 * 1000;
                } else if (s.length() > 1 && (s.endsWith("s") || s.endsWith("second") || s.endsWith("seconds"))) {
                    date += Integer.parseInt(s.substring(0, s.length() - 1)) * 1000;
                } else {
                    throw new NumberFormatException();
                }
            }
            return date;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return -1;
        }
    }
}

Related

  1. getTextBeforeFirstAndSecondColumns(String s)
  2. getTimeAsSeconds(String value)
  3. GetTimeFromSeconds(double time)
  4. getTimeFromSeconds(int seconds)
  5. getTimeInSecondResolution(long timeMillis)
  6. getTimeStringFromSeconds(int totalSeconds)
  7. getTokenRenewIntervalInSeconds(int tokenValidityInSeconds)
  8. getUnitLengthSeconds(String unit)
  9. getUnixTimeSeconds()