Top community members

Many years me and my friends we were volunteers on my university doing programming classes for young people.

I got main conclusion: Young people are awesome, especially students, because they always bring new and fresh ideas :)
* I loved to do it but my time is limited

  I decided to create something that will help millions of students

Now I am here

co-founder

[Edit]
EN

Java - convert String to Date

13 points
Created by:
Kate_C
2739

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

 

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more