Java Second Get getSeconds(String s)

Here you can find the source of getSeconds(String s)

Description

get Seconds

License

Open Source License

Parameter

Parameter Description
s time specification, number[s|m|h|d] for example, 10 : 10 seconds. 10s : 10 seconds. 12m : 12 minutes. 2h : 2 hours 5d : 5 days.

Return

the number of seconds in the specified string (10m = 60 seconds)

Declaration

public static int getSeconds(String s) 

Method Source Code

//package com.java2s;
/*/*from w  w  w.  jav  a2 s . c  o m*/
 * Copyright (C) ${year} Omry Yadan <${email}>
 * All rights reserved.
 *
 * See https://github.com/omry/banana/blob/master/BSD-LICENSE for licensing information
 */

public class Main {
    /**
     * @param s time specification, number[s|m|h|d] for example, 10 : 10 seconds.
     *          10s : 10 seconds. 12m : 12 minutes. 2h : 2 hours 5d : 5 days.
     * @return the number of seconds in the specified string (10m = 60 seconds)
     */
    public static int getSeconds(String s) {
        int k;
        if (s.length() == 1)
            return Integer.parseInt(s);

        char u = s.charAt(s.length() - 1);
        if (isInteger("" + u))
            return Integer.parseInt(s);

        float f = Float.parseFloat(s.substring(0, s.length() - 1));
        switch (u) {
        case 's':
            k = (int) (f);
            break;
        case 'm':
            k = (int) (f * 60);
            break;
        case 'h':
            k = (int) (f * 60 * 60);
            break;
        case 'd':
            k = (int) (f * 60 * 60 * 24);
            break;
        default:
            throw new RuntimeException("Unsupported unit type " + u
                    + ", supported units are s : seconds | m : minutes | h : hours | d : days");
        }

        return k;
    }

    public static boolean isInteger(String s) {
        try {
            if (s == null)
                return false;
            Integer.parseInt(s);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}

Related

  1. getSeconds(double coordinate)
  2. getSeconds(double seconds)
  3. getSeconds(double t)
  4. getSeconds(final double DEC_DEG)
  5. getSeconds(int minutes)
  6. getSeconds(String time)
  7. getSeconds(String time, int defaultValue)
  8. getSecondsAsClock(int time)
  9. getSecondsByDays(int days)