如何创建没有时间戳的java日期对象 [英] How do I create the java date object without time stamp

查看:413
本文介绍了如何创建没有时间戳的java日期对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个没有TimeZone的Date对象(例如: 2007-06-21 )。这可能吗?


当我使用以下方法时,打印像 Thu Jun 21 00:00:00 GMT 2007

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


推荐答案

如果要格式一个日期,你需要使用 DateFormat 或类似的东西。一个日期只是一个即时的时间 - 自Unix纪元以来的毫秒数。它不具有时区,日历系统或格式的任何想法。 toString()方法始终使用系统本地时区,并且始终以默认方式格式化。从文档

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:


将此Date对象转换为以下形式的字符串:

Converts this Date object to a String of the form:

dow mon dd hh:mm:ss zzz yyyy

dow mon dd hh:mm:ss zzz yyyy

所以它的行为与记录完全一样。

So it's behaving exactly as documented.

已经以正确的格式获得了一个 DateFormat ,所以您只需要调用格式

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.

请注意,如果这是与数据库的交互,最好不要将其传递为一个字符串。将值保持在本机表示形式尽可能多的时间,并使用类似 PreparedStatement.setDate 将其传递到数据库。

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.

除此之外,如果您可以更改为使用 Joda时间或Java 8中的新日期/时间API( java.time。* ),您将有更平滑的时间与任何日期/时间相关。 日期 / 日历 API真的很可怕。

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.

这篇关于如何创建没有时间戳的java日期对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆