How to convert String to Date object in java?
Hello to all,
I am new to this forum. I am just started learning java language. In last lecture our sir asked one question How to convert String to Date object in java? and none of us able to said the answer. That's why I am asking this question on this forum. Please help me.
Thank you.
Re: How to convert String to Date object in java?
Hey it is easy process to convert String to Date object in java. Just look at following example to understand how to convert String to Date object in java.
Code:
import java.text.*;
import java.util.*;
public class DateFormat
{
public DateFormat()
{
String dateS = "2009/04/10";
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy/mm/dd");
Date convertedD = dateFormat.parse(dateString);
System.out.println("Converting string to date : " + convertedD);
}
public static void main(String[] argv)
{
new DateFormat();
}
}
}
Re: How to convert String to Date object in java?
You have to use parse(String text) method to do this process. This method is used to parse date/time string into date and the return type of this method is Date. I have written example of this type.
Code:
import java.util.*;
import java.text.*;
public class StringToDate {
public static void main(String[] args) {
try { String strdate1="20-Jan-10";
DateFormat F1 ;
Date d1 ;
F1 = new SimpleDateFormat("dd-MMM-yy");
d1 = (Date)F1.parse(strdate1);
System.out.println("Date is " +d1 );
} catch (ParseException e)
{System.out.println("Exception :"+e); }
}
}
Re: How to convert String to Date object in java?
The following code shows how to convert String to Date object in java? In following example I had use java.text.SimpleDateFormat that extends java.text.DateFormat abstract class.
Code:
package org.kodejava.example.java.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
public class SToD
{
public static void main(String[] args)
{
DateFormat DF = new SimpleDateFormat("dd/MM/yyyy");
try
{
Date T1 = DF.parse("20/01/2010");
System.out.println("T1 = " + DF.format(T1));
} catch (ParseException e)
{
e.printStackTrace();
}
}
}
Re: How to convert String to Date object in java?
Following code example shows how to format a String to a Date object. In following example the method convertStringToDate actually takes three arguments as integers, date, month and year, and then concatenates these values to a String date.
Code:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/
public class Main {
public void convertStringToDate(int d, int m, int y) {
SimpleDateFormat dF = new SimpleDateFormat("dd/MM/yyyy");
String in = d + "/" + m + "/" + y;
try {
Date theD1 = dF.parse(in);
System.out.println("Date parsed = " + dF.format(theD1));
} catch (ParseException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Main().convertStringToDate(20, 11, 2010);
}
}