如何在 Java 中以 UTC 或 GMT 格式获取当前日期和时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/308683/
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
How can I get the current date and time in UTC or GMT in Java?
提问by Behrang
When I create a new Date
object, it is initialized to the current time but in the local timezone. How can I get the current date and time in GMT?
当我创建一个新Date
对象时,它被初始化为当前时间但在本地时区。如何获取格林威治标准时间的当前日期和时间?
采纳答案by Jon Skeet
java.util.Date
has no specific time zone, although its value is most commonly thought of in relation to UTC. What makes you think it's in local time?
java.util.Date
没有特定的时区,尽管它的值最常被认为与 UTC 相关。是什么让你觉得现在是当地时间?
To be precise: the value within a java.util.Date
is the number of milliseconds since the Unix epoch, which occurred at midnight January 1st 1970, UTC. The same epoch could also be described in other time zones, but the traditional description is in terms of UTC. As it's a number of milliseconds since a fixed epoch, the value within java.util.Date
is the same around the world at any particular instant, regardless of local time zone.
准确地说:a 中的值java.util.Date
是自 Unix 纪元以来的毫秒数,该纪元发生在 UTC 时间 1970 年 1 月 1 日午夜。同一个纪元也可以用其他时区来描述,但传统的描述是用 UTC 来描述的。由于它是固定纪元以来的毫秒数java.util.Date
,因此无论本地时区如何,世界各地的任何特定时刻的值都是相同的。
I suspect the problem is that you're displaying it via an instance of Calendar which uses the local timezone, or possibly using Date.toString()
which also uses the local timezone, or a SimpleDateFormat
instance, which, by default, also uses local timezone.
我怀疑问题在于您通过使用本地时区的 Calendar 实例显示它,或者可能使用Date.toString()
也使用本地时区的SimpleDateFormat
实例,或者默认情况下也使用本地时区的实例。
If this isn't the problem, please post some sample code.
如果这不是问题,请发布一些示例代码。
I would, however, recommend that you use Joda-Timeanyway, which offers a much clearer API.
但是,我建议您无论如何都使用Joda-Time,它提供了更清晰的 API。
回答by user2427
With:
和:
Calendar cal = Calendar.getInstance();
Then cal
have the current date and time.
You also could get the current Date and Time for timezone with:
然后cal
有当前的日期和时间。
您还可以通过以下方式获取时区的当前日期和时间:
Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("GMT-2"));
You could ask cal.get(Calendar.DATE);
or other Calendar constant about others details.
Date and Timestamp are deprecated in Java. Calendar class it isn't.
您可以询问cal.get(Calendar.DATE);
或其他日历常量有关其他详细信息。
Java 中不推荐使用日期和时间戳记。日历课不是。
回答by mjh2007
You can use:
您可以使用:
Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Then all operations performed using the aGMTCalendar object will be done with the GMT time zone and will not have the daylight savings time or fixed offsets applied. I think the previous poster is correct that the Date() object always returns a GMT it's not until you go to do something with the date object that it gets converted to the local time zone.
然后使用 aGMTCalendar 对象执行的所有操作都将使用 GMT 时区完成,并且不会应用夏令时或固定偏移量。我认为之前的海报是正确的,Date() 对象总是返回一个 GMT,直到你对它被转换为本地时区的日期对象做一些事情。
回答by Ahmad Nadeem
Calendar c = Calendar.getInstance();
System.out.println("current: "+c.getTime());
TimeZone z = c.getTimeZone();
int offset = z.getRawOffset();
if(z.inDaylightTime(new Date())){
offset = offset + z.getDSTSavings();
}
int offsetHrs = offset / 1000 / 60 / 60;
int offsetMins = offset / 1000 / 60 % 60;
System.out.println("offset: " + offsetHrs);
System.out.println("offset: " + offsetMins);
c.add(Calendar.HOUR_OF_DAY, (-offsetHrs));
c.add(Calendar.MINUTE, (-offsetMins));
System.out.println("GMT Time: "+c.getTime());
回答by Dan
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
//Local time zone
SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
//Time in GMT
return dateFormatLocal.parse( dateFormatGmt.format(new Date()) );
回答by simpatico
Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); Then all operations performed using the aGMTCalendar object will be done with the GMT time zone and will not have the daylight savings time or fixed offsets applied
日历 aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); 然后使用 aGMTCalendar 对象执行的所有操作都将使用 GMT 时区完成,并且不会应用夏令时或固定偏移量
Wrong!
错误的!
Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
aGMTCalendar.getTime(); //or getTimeInMillis()
and
和
Calendar aNotGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT-2"));aNotGMTCalendar.getTime();
will return the same time. Idem for
将在同一时间返回。同上
new Date(); //it's not GMT.
回答by Antonio
Actually not time, but it's representation could be changed.
实际上不是时间,但它的表示可以改变。
SimpleDateFormat f = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
f.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(f.format(new Date()));
Time is the same in any point of the Earth, but our perception of time could be different depending on location.
地球上任何地方的时间都是相同的,但我们对时间的感知可能因位置而异。
回答by Justin
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormatGmt.format(date));
回答by Someone Somewhere
This definitely returns UTC time: as String and Date objects !
这肯定会返回 UTC 时间:作为 String 和 Date 对象!
static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static Date getUTCdatetimeAsDate() {
// note: doesn't check for null
return stringDateToDate(getUTCdatetimeAsString());
}
public static String getUTCdatetimeAsString() {
final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String utcTime = sdf.format(new Date());
return utcTime;
}
public static Date stringDateToDate(String StrDate) {
Date dateToReturn = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMAT);
try {
dateToReturn = (Date)dateFormat.parse(StrDate);
}
catch (ParseException e) {
e.printStackTrace();
}
return dateToReturn;
}
回答by so_mv
Sample code to render system time in a specific time zone and a specific format.
以特定时区和特定格式呈现系统时间的示例代码。
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class TimZoneTest {
public static void main (String[] args){
//<GMT><+/-><hour>:<minutes>
// Any screw up in this format, timezone defaults to GMT QUIETLY. So test your format a few times.
System.out.println(my_time_in("GMT-5:00", "MM/dd/yyyy HH:mm:ss") );
System.out.println(my_time_in("GMT+5:30", "'at' HH:mm a z 'on' MM/dd/yyyy"));
System.out.println("---------------------------------------------");
// Alternate format
System.out.println(my_time_in("America/Los_Angeles", "'at' HH:mm a z 'on' MM/dd/yyyy") );
System.out.println(my_time_in("America/Buenos_Aires", "'at' HH:mm a z 'on' MM/dd/yyyy") );
}
public static String my_time_in(String target_time_zone, String format){
TimeZone tz = TimeZone.getTimeZone(target_time_zone);
Date date = Calendar.getInstance().getTime();
SimpleDateFormat date_format_gmt = new SimpleDateFormat(format);
date_format_gmt.setTimeZone(tz);
return date_format_gmt.format(date);
}
}
Output
输出
10/08/2011 21:07:21
at 07:37 AM GMT+05:30 on 10/09/2011
at 19:07 PM PDT on 10/08/2011
at 23:07 PM ART on 10/08/2011