Quantcast
Channel: Techie Shah
Viewing all articles
Browse latest Browse all 25

Java : How to convert String to Date?

$
0
0

 Introduction

In this post, we will learn how to convert Java String to Date 

Example:


import java.util.Date;
public class DateConversion {
	public static void main(String[] args) {		
	    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
	    try {
		Date date = sdf.parse("19-09-2020");
		System.out.println(date);
	    } catch (Exception ex) {
		ex.printStackTrace();
	    }
	}
}  

In Java 8 and onward versions, we can use the LocalDate and DateTimeFormatter class to convert a String to a LocalDate object. We will use the parse method of the LocalDate class to perform this conversion

Example (using Java 8+ versions)

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateConversion {
	public static void main(String[] args) {		
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
		try {
			LocalDate date = LocalDate.parse("19-09-2020",formatter);
			System.out.println(date);
		} catch (Exception ex) {
			ex.printStackTrace();
		}		
	}
}

Viewing all articles
Browse latest Browse all 25

Trending Articles