Categories
date java

convert String to date in java with example

In this tutorial, we will learn to convert String to date in java with example.While we working with java this is one of the most scenario

We can easily convert String to Data using SimpleDateFormat.java. But before that we should know the date patterns which mentioned below 

Letter Component Presentation Examples
yYearYear1996; 96
MMonth in yearMonthJuly; Jul; 07
dDay in monthNumber10
aAm/pm markerTextPM
HHour in day (0-23)Number0
kHour in day (1-24)Number24
KHour in am/pm (0-11)Number0
hHour in am/pm (1-12)Number12
mMinute in hourNumber30
sSecond in minuteNumber55
SMillisecondNumber978

In this example we will convert 20/02/2020 to Date class 

Syntax
DateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/YYYY");
 simpleDateFormat.parse(dateString);
Example

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

public class SimpleDateFormatExample {

	public static void main(String[] args) {
		try {
			String dateString = "20/02/2020";
			DateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/YYYY");
			// Below line will convert from string to date
			Date parse = simpleDateFormat.parse(dateString);
			// The output will be like Sun Dec 29 00:00:00 IST 2019
			System.out.println(" Output :: "+parse);
		} catch (ParseException e) {
			e.printStackTrace();
		}

	}

}
Output
 Output :: Sun Dec 29 00:00:00 IST 2019
Reference

https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html

Download

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/SimpleDateFormatExample.java

Related Articles

print current date in java with example

compare two dates in java example

Leave a Reply

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