Java program to convert string to date
www.igiftidea.com
Sure, here's a Java program that converts a string to a date:
import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class StringToDateConverter { public static void main(String[] args) { String strDate = "2023-02-16"; DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = dateFormat.parse(strDate); } catch (ParseException e) { e.printStackTrace(); } System.out.println(date); } }
In this program, we first create a string representation of the date we want to convert. We then create a DateFormat
object using the SimpleDateFormat
class, which specifies the format of the string. In this case, the format is "yyyy-MM-dd", which corresponds to the year, month, and day separated by hyphens.
We then use the parse
method of the DateFormat
object to convert the string to a Date
object. The parse
method can throw a ParseException
if the string cannot be parsed, so we enclose this call in a try
-catch
block.
Finally, we print out the Date
object to confirm that the conversion was successful.