Java TimeUnit Usage getTimeInMillis(String str)

Here you can find the source of getTimeInMillis(String str)

Description

Interprets a string specifying a time duration.

License

Apache License

Parameter

Parameter Description
str string value

Return

interpreted time duration in milliseconds

Declaration

public static long getTimeInMillis(String str) 

Method Source Code

//package com.java2s;
/*// w w  w . j  ava  2s  . c  om
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.concurrent.TimeUnit;

public class Main {
    /**
     * Interprets a string specifying a time duration. A time duration is specified as a long integer
     * followed by an optional d (days), h (hours), m (minutes), s (seconds), or ms (milliseconds). A
     * value without a unit is interpreted as seconds.
     *
     * @param str
     *          string value
     * @return interpreted time duration in milliseconds
     */
    public static long getTimeInMillis(String str) {
        TimeUnit timeUnit;
        int unitsLen = 1;
        switch (str.charAt(str.length() - 1)) {
        case 'd':
            timeUnit = TimeUnit.DAYS;
            break;
        case 'h':
            timeUnit = TimeUnit.HOURS;
            break;
        case 'm':
            timeUnit = TimeUnit.MINUTES;
            break;
        case 's':
            timeUnit = TimeUnit.SECONDS;
            if (str.endsWith("ms")) {
                timeUnit = TimeUnit.MILLISECONDS;
                unitsLen = 2;
            }
            break;
        default:
            timeUnit = TimeUnit.SECONDS;
            unitsLen = 0;
            break;
        }
        return timeUnit.toMillis(Long.parseLong(str.substring(0, str.length() - unitsLen)));
    }
}

Related

  1. getTime()
  2. getTimeComparisonEpsilonMicros()
  3. getTimeDifference(Date startDate, Date endDate)
  4. getTimeFormat(final long time)
  5. getTimeForS3URL()
  6. getTimeString(long millis)
  7. getTimezoneOffset(TimeZone timeZone)
  8. getTomorrowTimestamp()
  9. getUnit(long nanos)