Here you can find the source of parse(String s)
Parameter | Description |
---|---|
s | the date in string format |
public static Date parse(String s)
//package com.java2s; /*//from w ww. j av a 2 s . com * Copyright 2015 Adaptris Ltd. * * Licensed 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.text.DateFormat; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; public class Main { private static final String[] DATE_FORMATS = { "yyyy-MM-dd'T'HH:mm:ssZ", "yyyyMMdd HH:mm:ss zzz", "yyyyMMdd HH:mm:ss", "yyyyMMdd", "yyyy-MM-dd HH:mm:ss zzz", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd", "dd.MM.yyyy HH:mm:ss zzz", "dd.MM.yyyy HH:mm:ss", "dd.MM.yyyy", "dd/MM/yyyy HH:mm:ss zzz", "dd/MM/yyyy HH:mm:ss", "dd/MM/yyyy HH:mm:ss", "dd/MM/yyyy", }; /** * Return a date object from a given string. If the date could not be parsed, * the current time is used. * * @param s the date in string format * @return the date */ public static Date parse(String s) { if (s == null) { return new Date(); } Date date = useDefaultFormatter(s); int i = 0; while (date == null && i < DATE_FORMATS.length) { date = getDate(s, DATE_FORMATS[i++]); } return date == null ? new Date() : date; } private static Date useDefaultFormatter(String s) { DateFormat df = DateFormat.getDateTimeInstance(); return df.parse(s, new ParsePosition(0)); } private static Date getDate(String s, String format) { Date d = null; SimpleDateFormat sdf = new SimpleDateFormat(format); try { d = sdf.parse(s); } catch (ParseException e) { d = null; } return d; } }