Here you can find the source of stringToNanoseconds(String time)
Parameter | Description |
---|---|
time | the string to convert |
public static long stringToNanoseconds(String time)
//package com.java2s; /******************************************************************************* * Copyright (c) 2009, 2011 Ericsson/*from w w w . jav a2s.c om*/ * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * William Bourque - Initial API and implementation * Francois Chouinard - Cleanup and refactoring *******************************************************************************/ public class Main { /** * Convert a string representing a time to the corresponding long. * <p> * * @param time the string to convert * @return the corresponding nanoseconds value */ public static long stringToNanoseconds(String time) { long result = 0L; StringBuffer buffer = new StringBuffer(time); try { int dot = buffer.indexOf("."); //$NON-NLS-1$ // Prepend a "." if none was found (assume ns) if (dot == -1) { buffer.insert(0, "."); //$NON-NLS-1$ dot = 0; } // Zero-pad the string for nanoseconds for (int i = buffer.length() - dot - 1; i < 9; i++) buffer.append("0"); //$NON-NLS-1$ // Remove the extra decimals if present int nbDecimals = buffer.substring(dot + 1).length(); if (nbDecimals > 9) buffer.delete(buffer.substring(0, dot + 1 + 9).length(), buffer.length()); // Do the conversion long seconds = (dot > 0) ? Long.parseLong(buffer.substring(0, dot)) : 0; seconds = Math.abs(seconds); long nanosecs = Long.parseLong(buffer.substring(dot + 1)); result = seconds * 1000000000 + nanosecs; } catch (NumberFormatException e) { // TODO: Find something interesting to say } return result; } }