Java Conversion : String to Date

Here I am with another conversion method, today I’ll be showing you guys on how to convert a String data into a Date value. To do that we use a method named parse() method, before seeing this article you should know the Date and DateFormat class in Java first so you don’t get confused.

Here is a simple example on how parse() method works :

    import java.text.SimpleDateFormat; 
    import java.util.Date;  


    public class StringToDateExmpl{ 
    public static void main(String[] args)throws Exception { 
        String sDate=”04/01/2003″; 
        Date date=new SimpleDateFormat(“dd/MM/yyyy”).parse(sDate); //here we parse() it
        System.out.println(sDate+”t”+date1); //the “t” is just a command for “tab”
    } 
    }  


This program will output :

04/01/2003    Sat Jan 04 00:00:00 IST 2003

Here is a second example :
  import java.text.SimpleDateFormat;
   import java.util.Date;


    public class StringToDateExmpl2{ 
    public static void main(String[] args)throws Exception { 
        String sDate=”04-02-2003″; 
        Date date=new SimpleDateFormat(“dd-MM-yyyy”).parse(sDate); //here we parse() it
        System.out.println(sDate+”t”+date1); //the “t” is just a command for “tab”
    } 
    } 

This 2nd program will output :
04/02/2003    Thu Feb 04 00:00:00 IST 2003

P.s : notice that when I put the String in (04/01/2003) the parse() method also uses (dd/MM/yyyy) symbol, and when I put the String in (04-02-2003) the parse() method also uses (dd–MM–yyyy) symbol.

Published by

Rafif Santika

The programming language that I specialize in is Java, because I think Java programming language is more universal and of course because I like it regardless of any reason.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.