修改date格式 java,更改Date Java的格式

I've the Date object with the format

/107/2013 12:00:00 AM

Expected value for me:

2013-07-01

How I do this?.

I'm trying with this code

public static Date formatearFecha( Date fecha ){

String fechaString = new SimpleDateFormat("yyyy-MM-dd").format(fecha) ;

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

Date fechaFormateada = null;

try {

fechaFormateada = df.parse(fechaString);

} catch (ParseException ex) {

Logger.getLogger(TestThings.class.getName()).log(Level.SEVERE, null, ex);

}

return fechaFormateada;

}

When I try to make a test I get this:

System.out.println( formatearFecha(myDate) );

Mon Sep 30 00:00:00 COT 2013

Update:

my problem was in sql change to java.util.Date to java.sql.Date

I solve this so:

private String formatearFecha( Date fecha ){

return new SimpleDateFormat("yyyy-MM-dd").format(fecha);

}

private java.sql.Date stringToSQLDate( String fecString ){

java.sql.Date fecFormatoDate = null;

try {

SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd", new Locale("es", "ES"));

return new java.sql.Date(sdf.parse(fecString).getTime());

} catch (ParseException ex) { }

return null;

}

And test:

stringToSQLDate( formatearFecha( myDate ) );

解决方案

First of all: java.util.Date object never has a format stored in it. You can think of Date as an object containing long value of milliseconds since epoch at UTC timezone. The class has few methods, but no timezone offset, formatted pattern etc stored in it.

Secondly, following basic code can be used to format a date to yyyy-MM-dd in your machine's locale:

Date mydate = ...

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

String mydateStr = df.format(mydate);

Similarly, you can parse a string "/107/2013 12:00:00 AM" into a date object in your machine's locale like this:

String mydateStr = "/107/2013 12:00:00 AM";

DateFormat df = new SimpleDateFormat("/dMM/yyyy HH:mm:ss aa");

Date mydate = df.parse(mydateStr);

Two method above can be used to change a formatted date string from one into the other.

See the javadoc for SimpleDateFormat for more info about formatting codes.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值