Here you can find the source of dateFromString(String s)
Parameter | Description |
---|---|
s | The date as a String. |
public static Date dateFromString(String s)
//package com.java2s; /*// w ww. ja v a 2 s . c o m * (C) Copyright 2014 Fabien Barbero. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Main { private static final String DATE_REGEX = "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"; private static final DateFormat DATE_FORMAT = DateFormat.getDateInstance(); private static final String DATE_TIME_REGEX = "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$"; private static final DateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** * Get a date from a String. * * @param s The date as a String. * @return The date. */ public static Date dateFromString(String s) { if (s == null) { return null; } try { if (s.matches(DATE_REGEX)) { return DATE_FORMAT.parse(s); } else if (s.matches(DATE_TIME_REGEX)) { return DATE_TIME_FORMAT.parse(s); } else { long date = Long.parseLong(s); return new Date(date * 1000); } } catch (ParseException ex) { throw new UnsupportedOperationException("Error parsing date", ex); } } }