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
Apply timezone to Date object
提问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 Date
object? 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
Date
object uses the current timezone by default.If you are trying to print the time in specific timezone, you may use SimpleDateFormat
as 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
Date
objects 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 Date
adjusted for a timezone, then you can use SimpleDateFormatto apply the proper timezone adjustments.
如果您只是想显示Date
调整的时区,那么您可以使用SimpleDateFormat来应用正确的时区调整。