java读取mysql日期格式,在Java中转换MySQL日期格式

I am touching Java for the very first time here, so go easy on me. I am having to correct someone else's older code. This java program takes data from a MySQL table and prepares it for presentation on web pages. I found that their MySQL table for some reason used INT fields for all the dates. So, for instance, today's date is stored as the INT 3222017. I first had to add the proper DATE columns to the MySQL table. Next I re-did another Java script to pull the data from a larger table for the MySQL table that this script will be using.

Now I need to change the code that currently formats the INT fields into MM/dd/yyyy to instead take the DATE fields (stored as yyyy-MM-dd) and convert them to the same MM/dd/yyyy.

Here is a piece of the code that uses the function dateFormat on the INT fields -

String formattedDate = "";

formattedDate = dateFormat(oneSpectro.getSpectroLastDate());

result.setSpectroLastDate(formattedDate);

formattedDate = dateFormat(oneSpectro.getSpectroOrigDate());

result.setSpectroOrigDate(formattedDate);

formattedDate = dateFormat(oneSpectro.getSpectroCalDate());

result.setSpectroCalDate(formattedDate);

}

return result;

}

And here is the dateFormat function -

public String dateFormat(int theDate){

String dateString = "";

Integer dateInt = 0;

if (theDate < 10000000){

dateInt = new Integer(theDate);

dateString = dateInt.toString();

// Add preceding 0 to make the date 8 digits in length.

dateString = "0" + dateString;

}

else {

// Process an 8 digit date.

dateInt = new Integer(theDate);

dateString = dateInt.toString();

}

// Install date slashes in the date string.

if (dateString.length() == 8){

dateString = dateString.substring(0, 2) + "/" + dateString.substring(2, 4) + "/"

+ dateString.substring(4);

}

return dateString;

}

How do I go about converting a DATE field (yyyy-MM-dd) to a formatted date of MM/dd/yyyy?

解决方案

You can convert String to Date util:

DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);

Date date = format.parse(your string);

And then convert the Date object to your String format:

DateFormat df = new SimpleDateFormat("MM/dd/yyyy");

String result = df.format(date);

你可能感兴趣的:(java读取mysql日期格式)