Java util date with string

Guide to java.util.Date Class

Learn to create new date, get current date, parse date to string or format Date object using java.util.Date class. These usecases are frequently required, and having them in one place will help in saving time for many of us.

It is worth noting that there is no timezone information associated with Date instance. A Date instance represents the time spent since Epach in milliseconds. If we print the date instance, it always prints the default or local timezone of the machine. So the timezone information printed in Date.toString() method should not misguide you.

1. Formatting a Date to String

Java program of formatting Date to string using SimpleDateFormat.format() . Please note that SimpleDateFormat is not a thread-safe class, so we should not share its instance with multiple threads.

SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy"); String date = sdf.format(new Date());

Refer SimpleDateFormat JavaDoc for detailed date and time patterns. Below is a list of the most common pattern letters you can use.

y = year (yy or yyyy) M = month (MM) d = day in month (dd) h = hour (0-12) (hh) H = hour (0-23) (HH) m = minute in hour (mm) s = seconds (ss) S = milliseconds (SSS) z = time zone text (e.g. Pacific Standard Time. ) Z = time zone, time offset (e.g. -0800)
Pattern Example
yyyy-MM-dd (ISO) “2018-07-14”
dd-MMM-yyyy “14-Jul-2018”
dd/MM/yyyy “14/07/2018”
E, MMM dd yyyy “Sat, Jul 14 2018”
h:mm a “12:08 PM”
EEEE, MMM dd, yyyy HH:mm:ss a “Saturday, Jul 14, 2018 14:31:06 PM”
yyyy-MM-dd’T’HH:mm:ssZ “2018-07-14T14:31:30+0530”
hh ‘o»clock’ a, zzzz “12 o’clock PM, Pacific Daylight Time”
K:mm a, z “0:08 PM, PDT”
Читайте также:  Test

2. Parsing a String to Date

Java program of parsing a string to Date instance using SimpleDateFormat.parse() method.

SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss"); String dateInString = "15-10-2015 10:20:56"; Date date = sdf.parse(dateInString);

3. Getting Current Date and Time

java.util.Date class represents the date and time elapsed since the epoch. Given below are the Java programs for getting the current date and time and printing in a given format.

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); System.out.println(dateFormat.format(date)); 

For reference, since Java 8, we can use LocalDate , LocalTime and LocalDateTime classes.

LocalDate today = LocalDate.now(); System.out.println("Today's Local date : " + today); LocalTime time = LocalTime.now(); System.out.println("local time now : " + time);

4. Convert between Date and Calendar

4.1. Converting Calendar to Date

Calendar calendar = Calendar.getInstance(); Date date = calendar.getTime();

4.2. Converting Date to Calendar

SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss"); String dateInString = "27-04-2016 10:22:56"; Date date = sdf.parse(dateInString); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); 

We can compare two two date instances using its compareTo() method. It returns an integer value representing given date is before or after another date.

The comparison date1.CompareTo(date2) will return:

  • a value 0 if date2 is equal to date1;
  • a value less than 0 if date1 is before date2;
  • a value greater than 0 if date1 is after date2.
Date date1 = new Date(); Date date2 = new Date(); int comparison = date1.compareTo(date2);

6. Extracting Days, Months and Years

Java program to get date parts such as year, month, etc separately.

The methods to get the year, month, day of the month, hour, etc. are deprecated. If you need to get or set the year, month, day of the month, etc. use a java.util.Calendar instead.

Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); // Jan = 0, not 1 int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR); int weekOfMonth= calendar.get(Calendar.WEEK_OF_MONTH); int hour = calendar.get(Calendar.HOUR); // 12 hour clock int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY); // 24 hour clock int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); int millisecond= calendar.get(Calendar.MILLISECOND);

Источник

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.

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.

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,

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

Источник

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