Tuesday, January 19, 2016

Java String to Date with Example

In This Post we  will discuss how to convert String to Date. For this we use SimpleDateFormat class in java to convert java String to Date object. While developing software projects programmers constantly need  converting from Java String to Date or from Java Date to String object.so to convert Java String to Date object we use SimpleDateFormat class,this class can be find in java.text package.

Java provides two types of  Date classes from  different packages. they are 

a)java.util.Date
b)java.sql.Date

These two classes are use for creating Date Object. java.sql.Date class is used for whenever we are fetching or inserting the data into the database we used this type of Date class.java.util.Date class is used whenever to manipulate with the  java object.

you can also check the post: String  in java with examples



Steps how to convert java String to Date:

1.   First we need to create object for SimpleDateFormat class,this class is used  to specify  a date format(as a string)
Example:  SimpleDateFormat sdf=new SimpleDateFormat("dd/mm/yyyy");
    
2.   In the second step we need to use parse() method of SimpleDateFormat class that parse the String into Date Object it will return Date.

3. when we use Parse() method it might throw parseException so we need to handle it.

4. Finally use System.out.println() to see output on the screen.


Example:  Source Code:

import java.util.*;
import java.text.*;
class StringtoDateExample
{
public static void  main(String args[])
{
SimpleDateFormat  stformat=new SimpleDateFormat(" mmm ,dd, yyyy");
String str=" jan 19, 2016";

try{
Date date=stformat.parse(str);
System.out.println(dt);
System.out.println(stformat.format(dt));
}
catch(ParseException pe)
{
pe.printStackTrace();
}
}
}

Output:

After compiling and executing the java program you will get output like this

Tue Jan 19 00:00:00 IST
Jan 19,2016


Note: You can Convert String to Date  in java other format like dd-mm-yyyy as well

Example:

import java.util.*;
import java.text.*;
class StringtoDateExample
{
public static void  main(String args[])
{
SimpleDateFormat  stformat=new SimpleDateFormat(" dd-mmm-yyyy");
String str=" 19-jan-2016";
try{
Date date=stformat.parse(str);
System.out.println(dt);
System.out.println(stformat.format(dt));
}
catch(ParseException pe)
{
pe.printStackTrace();
}
}
}

OUTPUT:
Tue Jan 19 00:00:00 IST
19-jan-2016








No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...