Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting US date to EU date in java

Tags:

java

string

date

Without using a "dateformat" or something along those lines, I am trying to change a string of US date "mm/dd/yyyy" to an EU format "dd/mm/yyyy". I am to do this using strings and string methods. I feel like I am very close to this but cannot quite figure it out. This is my code:

import java.util.Scanner;

public class DateChange {

    public static void main(String[] args) {
        Scanner kbd = new Scanner(System.in);
        String usDate, euDate, day, month;
        int year;
        System.out.println("Enter a date in the form month/day/year:");
        usDate = kbd.nextLine();
        month = usDate.substring(0, '/');
        day = usDate.substring('/', '/');
        year = usDate.lastIndexOf('/');
        euDate = day + "." + month + "." + year;
        System.out.println("Your date in European form is:");
        System.out.println(euDate);
    }

}

This is the error I am getting:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 47
    at java.lang.String.substring(String.java:1963)
    at DateChange.main(DateChange.java:12)
like image 741
T3rm3nator Avatar asked Sep 19 '25 16:09

T3rm3nator


2 Answers

Why not split the input string using '/' as separator using the method String.split. It returns an array of strings. Just swap the first two elements of the array.

String usdate = "12/27/2015";
String[] arr = usdate.split("/");
String eudate = arr[1] + "/" + arr[0] + "/" + arr[2];
like image 53
Nayanjyoti Deka Avatar answered Sep 21 '25 07:09

Nayanjyoti Deka


The problem is that java.String.substring takes two int values, not char values. The int value of ' / ' is 47, so substring is taking 47 as an input, not the indexOf ' / '.

If you want to solve this without using the java library, use the following code:

import java.util.*;

public class DateChange {
    public static void main(String[] args) {
        Scanner kbd = new Scanner(System.in);
        String usDate, euDate, day = "", month = "", year = "";
        System.out.println("Enter a date in the form month/day/year:");
        usDate = kbd.nextLine();
        kbd.close();
        month = usDate.substring(0, usDate.indexOf("/"));
        day = usDate.substring(usDate.indexOf("/")+1, usDate.lastIndexOf("/"));
        year = usDate.substring(usDate.lastIndexOf("/")+1, usDate.length());
        euDate = day + "." + month + "." + year;
        System.out.println("Your date in European form is:");
        System.out.println(euDate);
    }
}
like image 33
DarkHorse Avatar answered Sep 21 '25 06:09

DarkHorse