Java converting from string to date

How To Convert String to Date in Java 8

Twitter Facebook Google Pinterest

A quick guide to converting String to Date in java And also example programs using Java 8 new Date API.

1. Overview

In this article, you’ll be learning how to convert String to Date in Java 8 as well as with Java 8 new DateTime API.

String date conversion can be done by calling the parse() method of LocalDate, DateFormat and SimpleDateFormat classes.

To convert a String to Date, first need to create the SimpleDateFormat or LocalDate object with the data format and next call parse() method to produce the date object with the contents of string date.

Java Convert String to Date (Java 8 LocalDate.parse() Examples)

First, let us write examples on string to date conversations with SimpleDateFormat classs and then next with DateFormat class.

All of the following classes are used to define the date format of input string. Simply to create the date formats.

2. How To Convert String To Date yyyy-MM-dd — SimpleDateFormat

So, First need to pass the date format of string to SimpleDateFormat class and then call parse() method of it. This method returns the String date in Date object format.

import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class SimpleFormatStringToDateExample1 < public static void main(String[] args) throws ParseException < String string = "2020-01-01"; System.out.println("Original string (that holds date value) : "+string); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd"); Date dateObject = dateFormatter.parse(string); System.out.println("Converted Date value : "+dateObject); >>
Original string (that holds date value) : 2020-01-01 Converted Date value : Wed Jan 01 00:00:00 IST 2020
Original string (that holds date value) : 2020-01-01 Exception in thread "main" java.text.ParseException: Unparseable date: "2020-01-01" at java.text.DateFormat.parse(DateFormat.java:366) at SimpleFormatStringToDateExample.main(SimpleFormatStringToDateExample.java:16)

3. How to convert string to date in java in dd-MM-yyyy format

import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class SimpleFormatStringToDateExample2 < public static void main(String[] args) throws ParseException < String string = "01-01-2020"; System.out.println("Original string (that holds date value) dd-MM-yyyy : "+string); SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy"); Date dateObject = dateFormatter.parse(string); System.out.println("Converted Date value : "+dateObject); >>
Original string (that holds date value) dd-MM-yyyy : 01-01-2020 Converted Date value : Wed Jan 01 00:00:00 IST 2020

4. How to format the String to Date? Examples on multiple date formats

Below program shows on string date in various formats that converts to the Date object with SimpleDateFormat class parse() method.

import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class MultipleFormatsStringToDateExample < public static void main(String[] args) throws ParseException < // string dates String stringDate1 = "31/01/2020"; String stringDate2 = "31-Jan-2020"; String stringDate3 = "12 31, 2020"; String stringDate4 = "Thu, Jan 31 2020"; String stringDate5 = "Thu, Jan 31 2020 23:37:50"; String stringDate6 = "31-Jan-2020 23:37:50"; // formatters SimpleDateFormat formatter1 = new SimpleDateFormat("dd/MM/yyyy"); SimpleDateFormat formatter2 = new SimpleDateFormat("dd-MMM-yyyy"); SimpleDateFormat formatter3 = new SimpleDateFormat("MM dd, yyyy"); SimpleDateFormat formatter4 = new SimpleDateFormat("E, MMM dd yyyy"); SimpleDateFormat formatter5 = new SimpleDateFormat("E, MMM dd yyyy HH:mm:ss"); SimpleDateFormat formatter6 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); // conversions Date date1 = formatter1.parse(stringDate1); Date date2 = formatter2.parse(stringDate2); Date date3 = formatter3.parse(stringDate3); Date date4 = formatter4.parse(stringDate4); Date date5 = formatter5.parse(stringDate5); Date date6 = formatter6.parse(stringDate6); System.out.println("String - Date values"); System.out.println(stringDate1 + " - " + date1); System.out.println(stringDate2 + " - " + date2); System.out.println(stringDate3 + " - " + date3); System.out.println(stringDate4 + " - " + date4); System.out.println(stringDate5 + " - " + date5); System.out.println(stringDate6 + " - " + date6); >>
String - Date values 31/01/2020 - Fri Jan 31 00:00:00 IST 2020 31-Jan-2020 - Fri Jan 31 00:00:00 IST 2020 12 31, 2020 - Thu Dec 31 00:00:00 IST 2020 Thu, Jan 31 2020 - Fri Jan 31 00:00:00 IST 2020 Thu, Jan 31 2020 23:37:50 - Fri Jan 31 23:37:50 IST 2020 31-Jan-2020 23:37:50 - Fri Jan 31 23:37:50 IST 2020

6. How to convert string to date in Java 8 with LocalDate Predefined Formatters

Java 8 api DateTimeFormatter class is added with a set of predefined formatters which are frequently used by the developers and those are the industry standards.

Читайте также:  Sudo update alternatives config php

This class helps to get the right formatters. Next pass the string date, formatter to LocalDate.parse() method which returns the date object.

import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Date; public class StringToDateExampleWithLocalDateWithPredefinedFormatters < public static void main(String[] args) throws ParseException < // string dates String isoDateInString = "2020-07-20"; DateTimeFormatter iso_date = DateTimeFormatter.ISO_DATE; LocalDate date = LocalDate.parse(isoDateInString, iso_date); System.out.println("Locale Date : "+date); >>

LocalDate.parse() method does the conversion the given string with the given formatter. Here, used ISO_DATE date formater which produces the date as «2020-07-20».

If the formatter is not matching to the string value then it throws the runtime exception. Change the formatter different as below.

DateTimeFormatter iso_date = DateTimeFormatter.BASIC_ISO_DATE;
Exception in thread "main" java.time.format.DateTimeParseException: Text '2020-07-20' could not be parsed at index 4 at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) at java.time.LocalDate.parse(LocalDate.java:400) at StringToDateExampleWithLocalDateWithPredefinedFormatters.main(StringToDateExampleWithLocalDateWithPredefinedFormatters.java:17)

7. How to convert string to date in Java 8 with LocalDate Custom Formatters

Now we are getting the date in the different format as «May 30, 2020» but for this, there is no predefined formatter. So now, How to convert the string to date object.

See the simple program to string date conversion:

import java.text.ParseException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class StringToDateExampleWithLocalDateWithCustomFormatters < public static void main(String[] args) throws ParseException < // string dates String isoDateInString = "May 30, 2020"; // custom formatter DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("MMM d, yyyy"); // string to date conversion in java 8 LocalDate date = LocalDate.parse(isoDateInString, customFormatter); // printing the date object System.out.println("Locale Date : "+date); >>

8. Java 8 DateTimeFormatter VS SimpleDateFormat

Java 8 api returns the LocalDate object as exact same as string content but SimpleDateFormat produces the Date objet which shows the full date with seconds by default even though time information is not provided.

import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Date; public class StringToDateExampleWithLocalDateWithCustomFormatters < public static void main(String[] args) throws ParseException < // string dates String isoDateInString = "May 30, 2020"; // Java 8 DateTimeFormatter // custom formatter DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("MMM d, yyyy"); // string to date conversion in java 8 LocalDate date = LocalDate.parse(isoDateInString, customFormatter); // printing the date object System.out.println("Java 8 DateTimeFormatter "+date); // Before java 8 - SimpleDateFormat SimpleDateFormat simpleCustomFormatter = new SimpleDateFormat("MMM d, yyyy"); Date simpleDate = simpleCustomFormatter.parse(isoDateInString); System.out.println("SimpleDateFomat : "+simpleDate); >>
Java 8 DateTimeFormatter 2020-05-30 SimpleDateFomat : Sat May 30 00:00:00 IST 2020

8. Conclusion

In this article, you’ve seen how to convert the String into Date using SimpleDateFormat.parse() and LocalDate.parse() method in Java 8.

Читайте также:  Java map foreach value

And also Example programs on Java 8 predefined formats and how to use the custom date formats in java 8.

Labels:

SHARE:

Twitter Facebook Google Pinterest

About Us

Java 8 Tutorial

  • Java 8 New Features
  • Java 8 Examples Programs Before and After Lambda
  • Java 8 Lambda Expressions (Complete Guide)
  • Java 8 Lambda Expressions Rules and Examples
  • Java 8 Accessing Variables from Lambda Expressions
  • Java 8 Method References
  • Java 8 Functional Interfaces
  • Java 8 — Base64
  • Java 8 Default and Static Methods In Interfaces
  • Java 8 Optional
  • Java 8 New Date Time API
  • Java 8 — Nashorn JavaScript

Java Threads Tutorial

Kotlin Conversions

Kotlin Programs

Java Conversions

  • Java 8 List To Map
  • Java 8 String To Date
  • Java 8 Array To List
  • Java 8 List To Array
  • Java 8 Any Primitive To String
  • Java 8 Iterable To Stream
  • Java 8 Stream To IntStream
  • String To Lowercase
  • InputStream To File
  • Primitive Array To List
  • Int To String Conversion
  • String To ArrayList

Java String API

  • charAt()
  • chars() — Java 9
  • codePointAt()
  • codePointCount()
  • codePoints() — Java 9
  • compareTo()
  • compareToIgnoreCase
  • concat()
  • contains()
  • contentEquals()
  • copyValueOf()
  • describeConstable() — Java 12
  • endsWith()
  • equals()
  • equalsIgnoreCase()
  • format()
  • getBytes()
  • getChars()
  • hashcode()
  • indent() — Java 12
  • indexOf()
  • intern()
  • isBlank() — java 11
  • isEmpty()
  • join()
  • lastIndexOf()
  • length()
  • lines()
  • matches()
  • offsetByCodePoints()
  • regionMatches()
  • repeat()
  • replaceFirst()
  • replace()
  • replaceAll()
  • resolveConstantDesc()
  • split()
  • strip(), stripLeading(), stripTrailing()
  • substring()
  • toCharArray()
  • toLowerCase()
  • transform() — Java 12
  • valueOf()

Spring Boot

$show=Java%20Programs

$show=Kotlin

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,

Читайте также:  Структура данных java map

A quick guide to converting String to Date in java And also example programs using Java 8 new Date API.

Источник

Java converting from string to date

Let’s see another code to convert different types of Strings to Date in java. Here, we have used different date formats using SimpleDateFormat class.

31/12/1998 Thu Dec 31 00:00:00 IST 1998 31-Dec-1998 Thu Dec 31 00:00:00 IST 1998 12 31, 1998 Thu Dec 31 00:00:00 IST 1998 Thu, Dec 31 1998 Thu Dec 31 00:00:00 IST 1998 Thu, Dec 31 1998 23:37:50 Thu Dec 31 23:37:50 IST 1998 31-Dec-1998 23:37:50 Thu Dec 31 23:37:50 IST 1998

Youtube

For Videos Join Our Youtube Channel: Join Now

Feedback

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью