Java Parse Time parseTime(String time)

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

Description

Returns Date from specified String time representation.

License

Open Source License

Parameter

Parameter Description
time String representation of Date

Exception

Parameter Description
ParseException when String is not valid Date representation

Return

Date from String time representation

Declaration

public static Date parseTime(String time) throws ParseException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    private static Pattern datePattern = null;

    /**//from ww w .  j  a v  a  2s.  co m
     * Returns Date from specified String time representation. String
     * representations must be in format YYYY-MM-DD HH:MM:SS (YYYY-year,
     * MM-month, DD-day; HH-hour, MM-minutes, SS-seconds).
     *
     * @param time
     *            String representation of Date
     * @return Date from String time representation
     * @throws ParseException
     *             when String is not valid Date representation
     */
    public static Date parseTime(String time) throws ParseException {

        if (datePattern == null) {
            datePattern = Pattern.compile("([0-9]{4})-([0-9]{2})-([0-9]{2}).([0-9]{2}):([0-9]{2}):([0-9]{2})");
        }
        Matcher matcher = datePattern.matcher(time);
        if (!matcher.matches()) {
            throw new ParseException("Bad date format [" + time + "]", 0);
        }

        try {

            int year = Integer.parseInt(matcher.group(1));
            int month = Integer.parseInt(matcher.group(2));
            int day = Integer.parseInt(matcher.group(3));
            int hour = Integer.parseInt(matcher.group(4));
            int minute = Integer.parseInt(matcher.group(5));
            int second = Integer.parseInt(matcher.group(6));

            Calendar cal = Calendar.getInstance();
            cal.clear();
            cal.set(year, month - 1, day, hour, minute, second);

            return cal.getTime();

        } catch (NumberFormatException ex) {
            throw new ParseException("Bad date format [" + time + "]", 0);
        }

    }
}

Related

  1. parseTime(String str)
  2. parseTime(String str)
  3. parseTime(String t)
  4. parseTime(String text)
  5. parseTime(String time)
  6. parseTime(String time, String formatStrBefore, String formatStrAfter)
  7. parseTime(String timestring)
  8. parseTime(String timeString, TimeZone timeZone)
  9. parseTime(String token)