Java uses the SimpleDateFormat
to parse dates from a String to a Date object.
Date date = null; try { date = new SimpleDateFormat("yyyy-MM-dd").parse( "2017-05-09" ); } catch (ParseException e1) { e1.printStackTrace(); }
This example first creates the String to parse "2017-05-09", then the formatter Object of type SimpleDateFormat
is created to parse the date. The method parse is called with the String as a parameter. The output value is stored in the date variable. That variable is then written in the output. If the String passed in not in the format defined by the pattern of the formatter, an exception is thrown.
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateStringFormatting { public static void main(String[] argv){ String dateString = "2017-05-09"; String pattern = "yyyy-MM-dd"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); Date date = null; try { date = simpleDateFormat.parse( dateString ); } catch (ParseException e) { e.printStackTrace(); } System.out.println( "Formatted date: " + date ); } }
Formatted date: Tue May 09 00:00:00 PDT 2017