java怎么创建日期,如何创建没有时间戳的java日期对象

I want to create a Date object without a TimeZone (eg : 2007-06-21). Is this possible?

When I use the following method it prints like Thu Jun 21 00:00:00 GMT 2007

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

TimeZone timeZone = TimeZone.getTimeZone("GMT");

timeZone.setDefault(timeZone);

sdf.setTimeZone(timeZone);

Date pickUpDate = sdf.parse("2007-06-21");

System.out.println(pickUpDate);

解决方案

If you want to format a date, you need to use DateFormat or something similar. A Date is just an instant in time - the number of milliseconds since the Unix epoch. It doesn't have any idea of time zone, calendar system or format. The toString() method always uses the system local time zone, and always formats it in a default way. From the documentation:

Converts this Date object to a String of the form:

dow mon dd hh:mm:ss zzz yyyy

So it's behaving exactly as documented.

You've already got a DateFormat with the right format, so you just need to call format on it:

System.out.println("pickUpDate" + sdf.format(pickUpDate));

Of course it doesn't make much sense in your sample, given that you've only just parsed it - but presumably you'd normally be passing the date around first.

Note that if this is for interaction with a database, it would be better not to pass it as a string at all. Keep the value in a "native" representation for as much of the time as possible, and use something like PreparedStatement.setDate to pass it to the database.

As an aside, if you can possibly change to use Joda Time or the new date/time API in Java 8 (java.time.*) you'll have a much smoother time of it with anything date/time-related. The Date/Calendar API is truly dreadful.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值