java 将时区应用于 Date 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13689456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:37:37  来源:igfitidea点击:

Apply timezone to Date object

javaandroid

提问by Johan

    Date now = new Date();
    Date then = new Date((long)obj.timestamp*1000);

    TimeZone tz = TimeZone.getDefault();

Not very familiar with java, but is there any way to apply a timezone to a Dateobject? I found thisthread, but this is about Calendar timezones, which i believe is something different?

对java不是很熟悉,但是有什么方法可以将时区应用于Date对象?我找到了这个线程,但这是关于日历时区的,我认为这是不同的?

采纳答案by PermGenError

use SimpleDateFormat.setTimeZone(TimeZone)to set TimeZone.

使用SimpleDateFormat.setTimeZone(TimeZone)设置时区。

    SimpleDateFormat sdf = new SimpleDateFormat("yourformat");   
    TimeZone tz = TimeZone.getDefault(); 
    sdf.setTimeZone(tz);
    sdf.format(yourdate); //will return a string rep of a date with the included format

回答by Yogendra Singh

Dateobject uses the current timezone by default.If you are trying to print the time in specific timezone, you may use SimpleDateFormatas below:

Date对象默认使用当前时区。如果您尝试打印特定时区的时间,您可以使用SimpleDateFormat如下:

   //put the desired format      
   DateFormat formatter= new SimpleDateFormat("MM/dd/yyyy hh:mm:ss Z");
   //set the desired timezone
   formatter.setTimeZone(TimeZone.getTimeZone("Europe/London"));

   String formattedNowInTimeZone  = formatter.format(now);
   String formattedThenInTimeZone  = formatter.format(then);

回答by Ralgha

Dateobjects do not have a timezone, it is simply a container for a specific moment in time. If you want to apply a timezone to it, you'll have to use a Calendar. I do it as follows

Date对象没有时区,它只是特定时间的容器。如果要对其应用时区,则必须使用Calendar. 我这样做如下

Calendar cal = Calendar.getInstance();
cal.setTime( date );

If you're just looking to display the Dateadjusted for a timezone, then you can use SimpleDateFormatto apply the proper timezone adjustments.

如果您只是想显示Date调整的时区,那么您可以使用SimpleDateFormat来应用正确的时区调整。