Java - Creating a Calendar without a TimeZone

孤者浪人 提交于 2019-12-18 17:36:31

问题


I would like to start by saying that I've read several threads similar to this one, but none of them really solved my problem. I would also like to state that I've tried to use SimpleDateFormat and joda.DateTime without any success.

The problem is the following:

I have a Calendar object that holds the information about a specific date: 2008-04-30T00:00:00Z When using the calendar.getTime() method I can get different results because I know that that method is looking for the local value

Thus:

UK: 2008-04-30T01:00:00.000+0100

US: 2008-04-30T20:00:00.000-0400

But I would like to get a Date object that holds just the Date and Time values "2008-04-30T00:00:00" ignoring completely any timezone.

How can I do that?

As I mentioned before I tried to use SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss") but I always end up with the same results.

Any help would be really appreciated Cheers.


回答1:


Found out that you can clear the Timezone by using code below:

Calendar cal = Calendar.getInstance(); cal.clear(Calendar.ZONE_OFFSET);




回答2:


Calendars and Dates mean nothing without a TimeZone.

Calendars and dates cannot exist without a timezone.

You can't ignore completely any timezone.

You can create a Calendar for Greenwich Mean Time (offset zero) like this:

    TimeZone zone = TimeZone.getTimeZone("Etc/GMT");
    Calendar cal = Calendar.getInstance(zone);

This represents a Date/Calendar that is only meaningful in the GMT timezone.

It sounds like you want a timestamp, which represents an instant in time.




回答3:


Do you use a standard constructor for initializing Calendar? What if you used the constructor which allows to specify the time zone and locale?

protected Calendar(TimeZone zone, Locale aLocale)



回答4:


As others have pointed out, Calendar and Date objects cannot exist without a time zone.

I believe you may want to use the LocalDateTime class introduced in Java 8 with the new time API:

LocalDateTime literal = LocalDateTime.of(2008, 4, 30, 0, 0, 0);
LocalDateTime parsed = LocalDateTime.parse("2008-04-30T00:00:00"); // ISO-8601 by default
Assert.assertEquals(literal, parsed);



回答5:


Old, but still incorrect.

"When using the calendar.getTime() method I can get different results because I know that that method is looking for the local value"

That is a misconception. getTime() will get the Milliseconds only. Countet as GMT.

ONLY during formatting of the Output the time zone becomes relevant. Sind the original poster did not show the code, it can not be decided, where the error occurs.



来源:https://stackoverflow.com/questions/11416914/java-creating-a-calendar-without-a-timezone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!