Here you can find the source of parseDateTime(String s)
Parameter | Description |
---|---|
s | the input string |
Parameter | Description |
---|---|
Exception | if the date cannot be parsed |
public static Calendar parseDateTime(String s) throws Exception
//package com.java2s; /**/*from www. j a va2 s . c om*/ * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. * * If it is not possible or desirable to put the notice in a particular file, * then You may include the notice in a location (such as a LICENSE file in a * relevant directory) where a recipient would be likely to look for such a * notice. * * */ import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; import java.util.GregorianCalendar; import java.util.Calendar; public class Main { /** * Parses the date/time stamp from a given input parameter using one of the * following formats<br> <ul> <li>mm/dd/yyyy</li> <li>mm/dd/yyyy * hh:mm:ss</li> <li>EEE MMM dd HH:mm:ss zzz yyyy - this is the standard * output from the unix date command</li> <li>EEE mm/dd/yyyy HH:mm:ss.ms - * this is the standard output from the windows command echo %date% * %time%</li> <li>yyyy-MM-ddThh:mm:ss.zzzzzzz</li> <li>Epoch time (ms)</li> * <li>PnYnMnDTnHnMnS - XML lexical representation</li> </ul> * * @param s the input string * @return a non-null instance of Calendar matching the interpreted date. * @throws Exception if the date cannot be parsed */ public static Calendar parseDateTime(String s) throws Exception { //this is what the calendar widget gives us SimpleDateFormat f1 = new SimpleDateFormat("MM/dd/yyyy"); SimpleDateFormat f2 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); //std unix date format SimpleDateFormat f3 = new SimpleDateFormat( "EEE MMM dd HH:mm:ss zzz yyyy"); //std windows date format SimpleDateFormat f4 = new SimpleDateFormat( "EEE MM/dd/yyyy HH:mm:ss.ms"); SimpleDateFormat f5 = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.zzzzzzz"); Date d = null; try { d = f1.parse(s, new ParsePosition(0)); } catch (Exception ex) { } if (d == null) { try { d = f2.parse(s, new ParsePosition(0)); } catch (Exception ex) { } } if (d == null) { try { d = f3.parse(s, new ParsePosition(0)); } catch (Exception ex) { } } if (d == null) { try { d = f4.parse(s, new ParsePosition(0)); } catch (Exception ex) { } } if (d == null) { try { d = f5.parse(s, new ParsePosition(0)); } catch (Exception ex) { } } if (d != null) { GregorianCalendar gcal = new GregorianCalendar(); gcal.setTime(d); return (gcal); } try { long timestamp = Long.parseLong(s); GregorianCalendar gcal = new GregorianCalendar(); gcal.setTimeInMillis(timestamp); return (gcal); } catch (Exception x) { } throw new Exception( "Unable to parse the date, see documentation for correct usage"); } }