Java String to Timestamp string2timestamp(String timeString)

Here you can find the source of string2timestamp(String timeString)

Description

stringtimestamp

License

Apache License

Declaration

public static long string2timestamp(String timeString) throws ParseException 

Method Source Code


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

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class Main {
    public static long string2timestamp(String timeString) throws ParseException {
        int decimalIndex = timeString.indexOf(".") + 1;
        String formatString;//from w  w w .j a  v a2 s . c om
        if (decimalIndex > 0) {
            formatString = timeString.substring(0, decimalIndex);
            int cnt = 0;
            while (decimalIndex < timeString.length() - 1 && cnt < 3) {
                formatString += timeString.substring(decimalIndex, decimalIndex + 1);
                decimalIndex++;
                cnt++;
            }
            while (cnt < 3) {
                formatString += "0";
                cnt++;
            }
            formatString += "Z";
        } else {
            formatString = timeString.substring(0, timeString.length() - 1) + ".000Z";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        Date date = sdf.parse(formatString);
        return date.getTime();
    }

    public static long string2timestamp(String timeString, TimeZone timeZone) throws ParseException {
        int decimalIndex = timeString.indexOf(".") + 1;
        String formatString;
        if (decimalIndex > 0) {
            formatString = timeString.substring(0, decimalIndex);
            int cnt = 0;
            while (decimalIndex < timeString.length() - 1 && cnt < 3) {
                formatString += timeString.substring(decimalIndex, decimalIndex + 1);
                decimalIndex++;
                cnt++;
            }
            while (cnt < 3) {
                formatString += "0";
                cnt++;
            }
            formatString += "Z";
        } else {
            formatString = timeString.substring(0, timeString.length() - 1) + ".000Z";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        sdf.setTimeZone(timeZone);
        Date date = sdf.parse(formatString);
        return date.getTime();
    }
}

Related

  1. getTimestampFromDateString(String date)
  2. getTimeStampInSecond(String timeStr)
  3. isTimestamp(String str, boolean allowEmpty)
  4. isTimeStampValid(String timestamp)
  5. string2Timestamp(String dateString, String timezone)
  6. stringToTimestamp(String date)
  7. timestamp(String string)
  8. timeStamp2Date(String timestampString)
  9. timeStampToDate(String timeStamp)