Skip to main content

How to Convert a String to Date in Java


How to Convert a String to Date in Java

Converting a string to a date in Java (or any programming language) is a fundamental skill and is useful to know when working on projects. Sometimes, it is easier to work with a string to represent a date, and then convert it to a date object for further use.

Date  API

The Date / Time API in Java works by default with the ISO 8601 format, which is (yyyy-MM-dd).By default all dates follow this format, and all strings that are converted should follow this if they are using the default formatter.

parse()

The date-time API provides parse () methods to parse a string that contains date information. To convert string objects to LocalDateTime objects, the string must represent a valid date or time according to ISO_LOCAL_DATE

Example, let's convert a String to a java.time.LocalDate:

LocalDate date = LocalDate.parse("2018-05-05");

Parse API with a Custom Formate

This format specifies three characters for the full day name of the week, one digit to represent the day of the month, three characters to represent the month, and four digits to represent the year.

String dateInString = "Mon, 05 May 1990";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, d MMM yyyy", Locale.ENGLISH);
LocalDate dateTime = LocalDate.parse(dateInString, formatter);

In this tutorial, we will show you how to convert a string to java.util.Date. Many Java are stuck in early date conversion, hope this summary guide will help you in some ways.

// String -> Date
    SimpleDateFormat.parse(String);

    // Date -> String
    SimpleDateFormat.format(date);

Common Date and Time Patterns

  • y – Year (1998; 98)
  • M – Month in year (July; Jul; 10)
  • d – Day in month (1-31)
  • E – Day name in week (Friday, Sunday)
  • a Am/pm marker (AM, PM)
  • H – Hour in day (0-23)
  • h – Hour in am/pm (1-12)
  • m – Minute in hour (0-60)
  • s – Second in minute (0-60)

Adding Time Zone Information to java.util.Date


It is important to note that java.util.Date has no concept of time zone, and only represents the number of seconds passed since the Unix era - 1979-01-01T00: 00: 00Z.
But, when we print the date object directly, it will always be printed with the Java default system time zone.
In this last example, we'll look at how to format the date by adding time zone information:

Convert String to Date: Function


After this section I have shared a complete example to display the string in various date formats for date conversion. For those who want only one function for this conversion, here is the function code:




// Java program to convert String to Date 
 
import java.time.Instant; 
import java.time.format.DateTimeParseException; 
 
class GFG { 
 
        // Function tot convert String to Date 
        public static Instant getDateFromString(String string) 
        { 
 
               // Create an Instant object 
               Instant timestamp = null; 
 
               // Parse the String to Date 
               timestamp = Instant.parse(string); 
 
               // return the converted timestamp 
               return timestamp; 
        } 
 
        public static void main(String[] args) 
        { 
               // Get the String 
               String string = "2018-10-28T15:23:01Z"; 
 
               // Get the Date from String 
               try { 
 
                       Instant timestamp = getDateFromString(string); 
 
                       // Print the converted Date 
                       System.out.println(timestamp); 
               } 
 
               // Throws DateTimeParseException 
               // if the string cannot be parsed 
               catch (DateTimeParseException e) { 
 
                       System.out.println("Exception: " + e); 
               } 
        } 
}
 
 
Output:

2018-10-28T15:23:01Z

Comments

Popular posts from this blog

Unity Mobile Game Optimization Checklist

- On Image and Text components that aren’t interacted with you can uncheck “Raycast Target” on it, as it will remove them from any Raycast calculus. - Click on your textures in your “Project” window. Click on the “Advanced” arrow, and now check “Generate Mip Maps”, Unity especially recommends it for faster texture loading time and a lower rendering time. - Set the “Shadow Cascades” to “No Cascades” (Quality settings) - If you have dynamic UI elements like a Scroll Rect with a lot of elements to visualize, a good practice is to turn off the pixel perfect check box on the canvas that contains the list and disable the items that aren’t visible on the screen. - Set all non moving objects to "Static" - Above Unity3d 2017.2 you should turn off "autoSyncTransforms" on the Physics tab - Always use Crunch Compression Low on textures - Try to keep the “Collision Detection Mode” on “Discrete” if possible, as “Dynamic” demands more performance. - You can go to the TimeManager w...

How to make RPC in Unreal Engine Steam Online Subsystem and EOS

Remote Procedure Calls, also known as RPCs, are a way to call something on any other instance.  In the Unreal Engine, RPCs are used to ship events from the patron to the server, the server to the customer, or from the server to a specific group. It's important to word that RPCs cannot have a return cost. If you want to return something, you'll ought to use a seconds RPC within the contrary path. There are precise policies that RPCs observe, which are unique in the official Documentation. Some of these regulations encompass wherein the RPC must be run, such as the server instance of an Actor, on the owner of the Actor, or on all instances of the Actor. There are some necessities for RPCs. First, they must be referred to as on Actors or replicated Subobjects. The Actor (and component) have to additionally be replicated. If the server is looking an RPC to be executed on a customer, handiest the patron who owns that Actor will execute the function. Similarly, if a client is calling...

How to fix clothes flickering in Unreal Engine 5.

 This issue can be noticed some of the character clothes when using Paragon Characters in UE5. To fix the flickering issue, Use Self Collisions checkbox in collisions properties under the Static Mesh option of your character. Open the character model go to   Asset Details > Clothing Properties - Cloth Config - ChaosClothConfig - Collision Properties - Use Self Collisions > False