Languages
[Edit]
EN

Java - convert String to Date

13 points
Created by:
Tehya-Blanchard
474

In Java, we can convert String to Date in couple of different ways.

Short solutions:

// solution 1
Date date1 = new SimpleDateFormat("dd/MM/yyyy").parse("24/12/2018");
// result: 
// Mon Dec 24 00:00:00 CET 2018

// solution 2
Date date2 = Date.from(LocalDate.parse("24/12/2018", DateTimeFormatter
        .ofPattern("dd/MM/yyyy")).atStartOfDay(ZoneId.systemDefault())
        .toInstant());
// result: 
// Mon Dec 24 00:00:00 CET 2018

1. Using SimpleDateFormat

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

public class Example1 {

    public static void main(String[] args) throws ParseException {
        String strDate = "24/12/2018";

        Date date = new SimpleDateFormat("dd/MM/yyyy").parse(strDate);
        System.out.println(date); // Mon Dec 24 00:00:00 CET 2018
    }
}

Output:

Mon Dec 24 00:00:00 CET 2018

2. Using DateTimeFormatter and LocalDate

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class Example2 {

    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        String strDate = "24/12/2018";

        LocalDate localDate = LocalDate.parse(strDate, formatter);
        Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault())
                .toInstant());

        System.out.println(date); // Mon Dec 24 00:00:00 CET 2018
    }
}

Output:

Mon Dec 24 00:00:00 CET 2018

Post summary image

Java - convert String to Date - Post summary image - dirask.com - link https://dirask.com/q/zjMxLp

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - String conversion

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