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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值