JAVA日期转换YY和yy,在Java中将dateTime转换为dd / mm / yy格式的日期

I have a JODA DateTime 2012-12-31T13:32:56.483+13:00. I would like to convert it to Date in dd/MM/yy format. So I'm expecting code to return Date like - 31/12/12.

Code -

// Input dateTime = 2012-12-31T13:32:56.483+13:00

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yy");

Date date = simpleDateFormat.parse(dateTime.toString("dd/MM/yy"));

Results:

Output - Mon Dec 31 00:00:00 NZDT 2012

Expected Output - 31/12/12

When I do the following, I get the expected output but I don't know how to convert it to Date-

String string = simpleDateFormat.format(date);

Please help me.

Thx

EDIT - I want my end result to be Util Date in dd/MM/yy format. I Do not want String output. My input is Joda DateTime yyyy-MM-ddThh:mm:ss:+GMT. I need to convert JodaDateTime to UtilDate.

解决方案

As I said originally, Date objects do not have an inherent format. java.util.Date holds a millisecond time value, representing both date & time. Dates are parsed from string, or formatted to string, via your choice of DateFormat.

The strings may be formatted per specification, but the Date objects behind them are always full precision & do not have any inherent notion of format.

To truncate a combined "date and time" java.util.Date to just the date component, leaving it effectively at midnight:

public static Date truncateTime (Date date) {

Calendar cal = Calendar.getInstance();

cal.setTime( date);

cal.set( Calendar.HOUR_OF_DAY, 0);

cal.set( Calendar.MINUTE, 0);

cal.set( Calendar.SECOND, 0);

cal.set( Calendar.MILLISECOND, 0);

return cal.getTime();

}

If you're coming from JodaTime DateTime, you can do this more easily working mostly in the JodaTime API.

public static Date truncateJodaDT (DateTime dt) {

java.util.Date result = dt.toDateMidnight().toDate();

return result;

}

Hope this helps!

See:

Now I'm unsure again, what you want. You want the date in string format now?

return simpleDateFormat.format( date); // from java.util.Date

Or with JodaTime:

return dateTime.toString( "dd/MM/yy"); // from org.joda.time.DateTime

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值