Java Milliseconds Parse getTimeMillis(String time)

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

Description

Transforms the string into a millisecond timestamp
- Days in d, day or days
- Hours in h, hour or hours
- Minutes in m, minute or minutes
- Seconds in s, second or seconds

returns -1 if the time cannot be transformed

License

Apache License

Parameter

Parameter Description
time The string form of this time

Exception

Parameter Description
NumberFormatException when a numer cannot be parsed.

Return

the time in millis

Declaration

public static long getTimeMillis(String time) 

Method Source Code

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

public class Main {
    /**// w w w  . ja va2  s. co  m
     * 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. changeMillSecond2Date(long millSeconds)
  2. getTimeAsMillis(String value)
  3. getTimeFromMilliseconds(long ms)
  4. getTimeInMilliseconds(String timeString)
  5. getTimeMillis(long FileTimestamp)
  6. parseDate(long millisec)
  7. parseGMTInMillis(String time)
  8. parseMillis(String s)
  9. parseMillisecond(String date)