-4

i have the following string: String date = "01/03/2010"; How to split this string to get separately the date,time and year? i want something like this

String date = "1/3/2010";

int date = 1
int month = 3
int year = 2010

padinal
  • 5
  • 2

4 Answers4

0
String string = "1/3/2010";
String[] parts = string.split("/");
String part1 = parts[0]; // 1
String part2 = parts[1]; //3
String part2 = parts[2]; //2010
04k
  • 175
  • 2
  • 8
0

You can use modern date-time API as shown below:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        String dateString = "01/03/2010";
        LocalDate date = LocalDate.parse(dateString, DateTimeFormatter.ofPattern("dd/MM/yyyy"));
        int day = date.getDayOfMonth();
        int month = date.getMonthValue();
        int year = date.getYear();
        System.out.println("Day: " + day + ", Month: " + month + ", Year: " + year);
    }
}

Output:

Day: 1, Month: 3, Year: 2010

Learn more about the modern date-time API at Trail: Date Time.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0
String dateString = "01/03/2010";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate localDate = LocalDate.parse(dateString, formatter);

int date = localDate.getDayOfMonth();
int month = localDate.getMonthValue();
int year = localDate.getYear();
0

You can use LocalDate instead of splitting the String.

String date = "1/3/2010";

// create a pattern that matches your date format
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("d/M/yyyy");

LocalDate parsed = LocalDate.parse(date, pattern);

You can then obtain various fields of the parsed LocalDate.

parsed.getDayOfMonth(); // 1
parsed.getMonthValue(); // 3
parsed.getYear());      // 2020
Glains
  • 2,773
  • 3
  • 16
  • 30