Languages
[Edit]
EN

Java - convert string to datetime

0 points
Created by:
Brett4
285

In this article, we would like to show you how to convert string to datetime in Java.

Quick solution:

String string = "27/07/2021 20:25:55";

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

Date date = formatter.parse(string);

System.out.println(date);  // Tue Jul 27 20:25:55 CEST 2021

 

Practical example

In this example, we present how to convert different types of string to datetime.

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

public class Example {

    public static void main(String[] args) throws ParseException {

        String string1 = "27/07/2021 20:25:55";
        String string2 = "27-Jul-2021 20:25:55";
        String string3 = "Tue, Jul 27 2021 20:25:55";

        SimpleDateFormat formatter1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        SimpleDateFormat formatter2 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
        SimpleDateFormat formatter3 = new SimpleDateFormat("E, MMM dd yyyy HH:mm:ss");

        Date date1 = formatter1.parse(string1);
        Date date2 = formatter2.parse(string2);
        Date date3 = formatter3.parse(string3);

        System.out.println(date1);  // Tue Jul 27 20:25:55 CEST 2021
        System.out.println(date2);  // Tue Jul 27 20:25:55 CEST 2021
        System.out.println(date3);  // Tue Jul 27 20:25:55 CEST 2021
    }
}

Output:

Tue Jul 27 20:25:55 CEST 2021
Tue Jul 27 20:25:55 CEST 2021
Tue Jul 27 20:25:55 CEST 2021
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join