简体   繁体   English

将日历转换为java.util.Date时出现问题

[英]problem converting calendar to java.util.Date

I need to create a java.util.Date object with an Australian timezone. 我需要使用澳大利亚时区创建一个java.util.Date对象。 this object is required for tag libraries used in downstream components (so I'm stuck with Date). 该对象是下游组件中使用的标记库所必需的(因此,我对Date不满意)。

Here's what I have attempted: 这是我尝试过的:

TimeZone timeZone = TimeZone.getTimeZone("Australia/Sydney");
GregorianCalendar defaultDate = new GregorianCalendar(timeZone);
Date date = defaultDate.getTime();

However, "date" always returns the current local time (in my case, ET). 但是,“日期”始终返回当前本地时间(在我的情况下为ET)。 What am I doing wrong here? 我在这里做错了什么? Is it even possible to set a Date object with a different timezone? 甚至可以用不同的时区设置Date对象吗?

Update: 更新:

Thanks for the responses! 感谢您的回复! This works if I want to output the formatted date as a string, but not if I want to return a date object. 如果我想将格式化的日期输出为字符串,这是可行的,但是如果我想返回日期对象,则不会。 Ex: 例如:

Date d = new Date();
DateFormat df = new SimpleDateFormat();
df.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));

String formattedDate = df.format(d);   // returns Sydney date/time
Date myDate = df.parse(formattedDate); // returns local time(ET)

I think I'm going to end up reworking our date taglib. 我想我最终将重新设计我们的日期标签库。

Is it even possible to set a Date object with a different timezone? 甚至可以用不同的时区设置Date对象吗?

No, it's not possible. 不,不可能。 As its javadoc describes, all the java.util.Date contains is just the epoch time which is always the amount of seconds relative to 1 january 1970 UTC/GMT. 正如其javadoc描述的那样,所有java.util.Date包含的只是纪元时间,始终是相对于1970年1月1日UTC / GMT的秒数。 The Date doesn't contain other information. Date不包含其他信息。 To format it using a timezone, use SimpleDateFormat#setTimeZone() 要使用时区对其进行格式化,请使用SimpleDateFormat#setTimeZone()

getTime is an Unix time in seconds, it doesn't have the timezone, ie it's bound to UTC. getTime是一个以秒为单位的Unix时间,它没有时区,即与UTC绑定。 You need to convert that time to the time zone you want eb by using DateFormat. 您需要使用DateFormat将时间转换为您想要的时区。

import java.util.*;
import java.text.*;

public class TzPrb {
    public static void main(String[] args) {
        Date d = new Date();
        System.out.println(d);

        DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        df.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
        System.out.println(df.format(d));
        df.setTimeZone(TimeZone.getTimeZone("Europe/London"));
        System.out.println(df.format(d));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM