Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String to Date in java whatever system format is [duplicate]

Tags:

java

string

I'm trying to convert a date string to date object in java regardless of current system date format. Because I want to get my custom date format to store in database. The following is my code and please advice me the way.

public static String dateToString(String date){
    if(date.equals("")) return "";
    if(date == null || date.length() == 0){
        return "";
    }
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    try {
        Date l_date =  format.parse(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(l_date);
        String year = String.format("%04d", calendar.get(Calendar.YEAR));
        String month = String.format("%02d", calendar.get(Calendar.MONTH));
        String day = String.format("%02d", calendar.get(Calendar.DATE));
        return year + month + day;
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "";
    }
}

For SimpleDateFormat, it can only parse the format I heard coded.

dateToString("16/04/2015");

It can convert for above code. But, when I try with the following format

dateToString("Thursday, April 16, 2015");

I go Unparseable date: "Thursday, April 16, 2015" error.

like image 585
Thiha Zaw Avatar asked Apr 16 '15 07:04

Thiha Zaw


1 Answers

You're trying to convert a String in EEEE, MMMM dd, yyyy format with the format of dd/MM/yyyy...

Start by using the correct format for the String you trying to convert, the use what ever format you want to convert it back...

SimpleDateFormat from = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
SimpleDateFormat to = new SimpleDateFormat("dd/MM/yyyy");

String value = to.format(from.parse(dateString));

Now you could use something like DateUtils.parseDate(String, String[]) which allows to supply a number of different formats, but is still limited to what you might know.

A better solution would be to store the Date value directly within the database.

like image 98
MadProgrammer Avatar answered Sep 29 '22 04:09

MadProgrammer