在UTC或GMT时,如何获得当前的日期和时间?

时间:2021-02-13 16:01:16

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对象时,它被初始化为当前时间,但是在本地时区中。我怎样才能得到现在的日期和时间?

28 个解决方案

#1


325  

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。日期没有特定的时区,尽管它的值通常被认为与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.

精确地说:java.util中的值。日期是Unix纪元以来的毫秒数,它发生在1970年1月1日午夜UTC。在其他时区也可以描述相同的时代,但是传统的描述是UTC。因为它是一个固定的纪元以来的几毫秒,java.util中的值。在任何特定的瞬间,世界各地的日期都是相同的,无论当地时区。

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.

我怀疑问题在于,您通过使用本地时区的日历实例来显示它,或者可能使用Date.toString(),它还使用本地时区,或者一个SimpleDateFormat实例,默认情况下,它也使用本地时区。

If this isn't the problem, please post some sample code.

如果这不是问题,请张贴一些示例代码。

I would, however, recommend that you use Joda-Time anyway, which offers a much clearer API.

但是,我建议您使用Joda-Time,它提供了一个更加清晰的API。

#2


241  

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()) );

#3


163  

tl;dr

Instant.now()

Generate a String to represent that value:

生成一个字符串来表示该值:

Instant.now().toString()  

2016-09-13T23:30:52.123Z

2016 - 09 - 13 - t23:30:52.123z

Details

As the correct answer by Jon Skeet stated, a java.util.Date object has no time zone. But its toString implementation applies the JVM’s default time zone when generating the String representation of that date-time value. Confusingly to the naïve programmer, a Date seems to have a time zone but does not.

正如Jon Skeet所指出的正确答案,一个java.util。日期对象没有时区。但是它的toString实现在生成该日期时间值的字符串表示时应用JVM的默认时区。对于天真的程序员来说,一个日期似乎有一个时区,但却没有。

The java.util.Date, j.u.Calendar, and java.text.SimpleDateFormat classes bundled with Java are notoriously troublesome. Avoid them. Instead, use either of these competent date-time libraries:

java.util。日期、j.u。日历和text。与Java绑定的SimpleDateFormat类是出了名的麻烦。避免它们。相反,可以使用这些有能力的日期时间库:

java.time (Java 8)

Java 8 brings an excellent new java.time.* package to supplant the old java.util.Date/Calendar classes.

Java 8带来了一个优秀的新Java .time。包以取代旧的java.util。日期/日历类。

Getting current time in UTC/GMT is a simple one-liner…

在UTC/GMT获得当前时间是一个简单的一行程序…

Instant instant = Instant.now();

That Instant class is the basic building block in java.time, representing a moment on the timeline in UTC with a resolution of nanoseconds.

这个即时类是java中的基本构建块。时间,表示在UTC时间轴上的一个瞬间,它的分辨率为纳秒。

In Java 8, the current moment is captured with only up to milliseconds resolution. Java 9 brings a fresh implementation of Clock captures the current moment in up to the full nanosecond capability of this class, depending on the ability of your host computer’s clock hardware.

在Java 8中,当前的时刻仅以毫秒的分辨率捕获。Java 9带来了一个新实现的时钟捕捉当前时刻,在这类的全部纳秒能力,取决于你的主机的时钟硬件的能力。

It’s toString method generates a String representation of its value using one specific ISO 8601 format. That format outputs zero, three, six or nine digits digits (milliseconds, microseconds, or nanoseconds) as necessary to represent the fraction-of-second.

它的toString方法使用一个特定的ISO 8601格式生成它的值的字符串表示。该格式输出0、3、6或9位数字(毫秒、微秒或纳秒),以表示秒的动作。

If you want more flexible formatting, adjustments in or out of various time zones, or other additional features, then apply a time zone (ZoneId object) to get a ZonedDateTime. The time zone can be for UTC or any other time zone. The subclass of ZoneId, ZoneOffset holds a constant for UTC.

如果您想要更灵活的格式化,可以在不同的时区或其他额外的特性中进行调整,然后应用一个时区(ZoneId对象)来获得一个ZonedDateTime。时区可以是UTC或任何其他时区。ZoneId的子类,ZoneOffset为UTC保留一个常量。

ZonedDateTime now = ZonedDateTime.now( ZoneOffset.UTC );

Dump to console…

转储控制台……

System.out.println( "now: " + now );

When run…

运行时……

now: 2014-01-21T23:42:03.522Z

The java.time classes are defined by JSR 310. They were inspired by Joda-Time but are entirely re-architected.

java。时间类由JSR 310定义。他们受到了joda时间的启发,但完全重新架构了。

Joda-Time

UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

更新:Joda-Time项目,现在在维护模式,建议迁移到java。时间类。

Using the Joda-Time 3rd-party open-source free-of-cost library, you can get the current date-time in just one line of code.

使用Joda-Time第三方开源免费库,您可以在一行代码中获得当前的日期时间。

Joda-Time inspired the new java.time.* classes in Java 8, but has a different architecture. You may use Joda-Time in older versions of Java. Joda-Time continues to work in Java 8 and continues to be actively maintained (as of 2014). However, the Joda-Time team does advise migration to java.time.

新java.time Joda-Time启发。*类在Java 8中,但却具有不同的结构。你可以用Joda-Time旧版本的Java。Joda-Time继续在Java 8工作,继续积极维护(截至2014年)。然而,Joda-Time团队并建议迁移java.time。

System.out.println( "UTC/GMT date-time in ISO 8601 format: " + new org.joda.time.DateTime( org.joda.time.DateTimeZone.UTC ) );

More detailed example code (Joda-Time 2.3)…

更详细的示例代码(Joda-Time 2.3)…

org.joda.time.DateTime now = new org.joda.time.DateTime(); // Default time zone.
org.joda.time.DateTime zulu = now.toDateTime( org.joda.time.DateTimeZone.UTC );

Dump to console…

转储控制台……

System.out.println( "Local time in ISO 8601 format: " + now );
System.out.println( "Same moment in UTC (Zulu): " + zulu );

When run…

运行时……

Local time in ISO 8601 format: 2014-01-21T15:34:29.933-08:00
Same moment in UTC (Zulu): 2014-01-21T23:34:29.933Z

For more example code doing time zone work, see my answer to a similar question.

对于更多的示例代码执行时区工作,请参见我对类似问题的回答。

Time Zone

I recommend you always specify a time zone rather than relying implicitly on the JVM’s current default time zone (which can change at any moment!). Such reliance seems to be a common cause of confusion and bugs in date-time work.

我建议您总是指定一个时区,而不是隐式地依赖JVM的当前默认时区(随时可以更改!)这种依赖似乎是在时间工作中造成混乱和错误的常见原因。

When calling now() pass the desired/expected time zone to be assigned. Use the DateTimeZone class.

当调用now()时,传递所需的/预期的时区。使用DateTimeZone时区类。

DateTimeZone zoneMontréal = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zoneMontréal );

That class holds a constant for UTC time zone.

这个类对UTC时区保持不变。

DateTime now = DateTime.now( DateTimeZone.UTC );

If you truly want to use the JVM’s current default time zone, make an explicit call so your code is self-documenting.

如果您确实想要使用JVM的当前默认时区,那么就进行显式调用,这样您的代码就可以自我记录了。

DateTimeZone zoneDefault = DateTimeZone.getDefault();

ISO 8601

Read about ISO 8601 formats. Both java.time and Joda-Time use that standard’s sensible formats as their defaults for both parsing and generating strings.

读到ISO 8601格式。java。时间和Joda-Time使用标准的合理的格式解析和生成字符串作为其默认值。


Actually, java.util.Date does have a time zone, buried deep under layers of source code. For most practical purposes, that time zone is ignored. So, as shorthand, we say java.util.Date has no time zone. Furthermore, that buried time zone is not the one used by Date’s toString method; that method uses the JVM’s current default time zone. All the more reason to avoid this confusing class and stick with Joda-Time and java.time.

†实际上,java.util。日期有一个时区,深埋层的源代码。对于大多数实用目的,时区被忽略。所以,作为速记,我们说java.util。日期没有时区。此外,埋时区不使用的一个约会对象的toString方法;该方法使用JVM当前的默认时区。更有理由避免这种混淆类和坚持Joda-Time java.time。

#4


73  

This definitely returns UTC time: as String and Date objects !

这个肯定返回UTC时间:字符串和约会对象!

static final String DATEFORMAT = "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(DATEFORMAT);
    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;
}

#5


65  

    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());

#6


48  

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.

地球上任何地方的时间都是相同的,但我们对时间的感知可能会因地点不同而有所不同。

#7


15  

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(格林尼治时间));然后使用aGMTCalendar对象执行的所有操作将完成了时区和格林尼治时间没有日光节约时间或固定补偿

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.

#8


12  

This works for getting UTC milliseconds in Android.

这适用于在Android上获得UTC毫秒。

Calendar c = Calendar.getInstance();
int utcOffset = c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET);  
Long utcMilliseconds = c.getTimeInMillis() + utcOffset;

#9


12  

This code prints the current time UTC.

此代码打印当前UTC时间。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;


public class Test
{
    public static void main(final String[] args) throws ParseException
    {
        final SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
        f.setTimeZone(TimeZone.getTimeZone("UTC"));
        System.out.println(f.format(new Date()));
    }
}

Result

结果

2013-10-26 14:37:48 UTC

#10


9  

Jon Skeet asks:

Jon水瓢问道:

@Downvoter: Care to comment? What exactly is incorrect in my answer? – Jon Skeet Oct 26 '09 at 21:09

@Downvoter:想发表意见吗?我的回答到底有什么错误?- Jon Skeet 2009年10月26日21:09。

I am not the Downvoter, but here is what seems to be incorrect in that answer. You said:

我不是消极的选民,但在这个问题上,这似乎是不正确的。你说:

java.util.Date is always in UTC. What makes you think it's in local time? 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.

java.util。日期总是在UTC。是什么让你认为是在当地时间?我怀疑问题是您通过使用本地时区的日历实例来显示它,或者可能使用Date.toString(),它也使用本地时区。

However, the code:

然而,代码:

System.out.println(new java.util.Date().getHours() + " hours");

gives the local hours, not GMT (UTC hours), using no Calendar and no SimpleDateFormat at all.

提供本地时间,而不是GMT (UTC小时),没有使用日历,也没有SimpleDateFormat。

That is why is seems something is incorrect.

这就是为什么有些事情似乎是不正确的。

Putting together the responses, the code:

把这些回应,代码:

System.out.println(Calendar.getInstance(TimeZone.getTimeZone("GMT"))
                           .get(Calendar.HOUR_OF_DAY) + " Hours");

shows the GMT hours instead of the local hours -- note that getTime.getHours() is missing because that would create a Date() object, which theoretically stores the date in GMT, but gives back the hours in the local time zone.

显示的是GMT时间,而不是本地时间——请注意getTime.getHours()丢失了,因为它将创建一个Date()对象,该对象理论上存储了GMT的日期,但是返回了本地时区的时间。

#11


7  

If you want a Date object with fields adjusted for UTC you can do it like this with Joda Time:

如果你想要一个与UTC相适应的日期对象,你可以用Joda时间来这样做:

import org.joda.time.DateTimeZone;
import java.util.Date;

...

Date local = new Date();
System.out.println("Local: " + local);
DateTimeZone zone = DateTimeZone.getDefault();
long utc = zone.convertLocalToUTC(local.getTime(), false);
System.out.println("UTC: " + new Date(utc));

#12


6  

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时区完成,并且不会使用夏令时或固定的偏移量。我认为前面的海报是正确的,日期()对象总是返回一个GMT常量,直到你去做一些与日期对象相关的事情,它才会被转换到本地时区。

#13


6  

SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormatGmt.format(date));

#14


5  

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中不推荐日期和时间戳。它不是日历类。

#15


5  

Here an other suggestion to get a GMT Timestamp object:

这里还有一个建议,可以得到一个GMT时间戳对象:

import java.sql.Timestamp;
import java.util.Calendar;

...

private static Timestamp getGMT() {
   Calendar cal = Calendar.getInstance();
   return new Timestamp(cal.getTimeInMillis()
                       -cal.get(Calendar.ZONE_OFFSET)
                       -cal.get(Calendar.DST_OFFSET));
}

#16


5  

Here is another way to get GMT time in String format

这里还有另一种方法,以字符串格式获取GMT时间。

String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z" ;
final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String dateTimeString =  sdf.format(new Date());

#17


5  

You can directly use this

你可以直接用这个。

SimpleDateFormat dateFormatGmt = new SimpleDateFormat("dd:MM:yyyy HH:mm:ss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormatGmt.format(new Date())+"");

#18


4  

Just to make this simpler, to create a Date in UTC you can use Calendar :

为了让这个更简单,在UTC中创建一个日期,你可以使用日历:

Calendar.getInstance(TimeZone.getTimeZone("UTC"));

Which will construct a new instance for Calendar using the "UTC" TimeZone.

它将使用“UTC”时区构造一个新的日历实例。

If you need a Date object from that calendar you could just use getTime().

如果您需要从该日历上的日期对象,您可以使用getTime()。

#19


3  

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

#20


3  

Converting Current DateTime in UTC:

在UTC中转换当前的DateTime:

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

DateTimeZone dateTimeZone = DateTimeZone.getDefault(); //Default Time Zone

DateTime currDateTime = new DateTime(); //Current DateTime

long utcTime = dateTimeZone.convertLocalToUTC(currDateTime .getMillis(), false);

String currTime = formatter.print(utcTime); //UTC time converted to string from long in format of formatter

currDateTime = formatter.parseDateTime(currTime); //Converted to DateTime in UTC

#21


2  

This worked for me, returns the timestamp in GMT!

这对我起作用了,在GMT时返回时间戳!

    Date currDate;
    SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
    dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
    SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");

    long currTime = 0;
    try {

        currDate = dateFormatLocal.parse( dateFormatGmt.format(new Date()) );
        currTime = currDate.getTime();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

#22


2  

public static void main(String args[]){
    LocalDate date=LocalDate.now();  
    System.out.println("Current date = "+date);
}

#23


1  

To put it simple. A calendar object stores information about time zone but when you perform cal.getTime() then the timezone information will be lost. So for Timezone conversions I will advice to use DateFormat classes...

把它简单。日历对象存储关于时区的信息,但是当您执行cal.getTime()时,时区信息就会丢失。因此,对于时区转换,我将建议使用DateFormat类…

#24


1  

Use this Class to get ever the right UTC Time from a Online NTP Server:

使用这个类从一个在线的NTP服务器获得正确的UTC时间:

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


class NTP_UTC_Time
{
private static final String TAG = "SntpClient";

private static final int RECEIVE_TIME_OFFSET = 32;
private static final int TRANSMIT_TIME_OFFSET = 40;
private static final int NTP_PACKET_SIZE = 48;

private static final int NTP_PORT = 123;
private static final int NTP_MODE_CLIENT = 3;
private static final int NTP_VERSION = 3;

// Number of seconds between Jan 1, 1900 and Jan 1, 1970
// 70 years plus 17 leap days
private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;

private long mNtpTime;

public boolean requestTime(String host, int timeout) {
    try {
        DatagramSocket socket = new DatagramSocket();
        socket.setSoTimeout(timeout);
        InetAddress address = InetAddress.getByName(host);
        byte[] buffer = new byte[NTP_PACKET_SIZE];
        DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);

        buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);

        writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET);

        socket.send(request);

        // read the response
        DatagramPacket response = new DatagramPacket(buffer, buffer.length);
        socket.receive(response);          
        socket.close();

        mNtpTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);            
    } catch (Exception e) {
      //  if (Config.LOGD) Log.d(TAG, "request time failed: " + e);
        return false;
    }

    return true;
}


public long getNtpTime() {
    return mNtpTime;
}


/**
 * Reads an unsigned 32 bit big endian number from the given offset in the buffer.
 */
private long read32(byte[] buffer, int offset) {
    byte b0 = buffer[offset];
    byte b1 = buffer[offset+1];
    byte b2 = buffer[offset+2];
    byte b3 = buffer[offset+3];

    // convert signed bytes to unsigned values
    int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
    int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
    int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
    int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);

    return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
}

/**
 * Reads the NTP time stamp at the given offset in the buffer and returns 
 * it as a system time (milliseconds since January 1, 1970).
 */    
private long readTimeStamp(byte[] buffer, int offset) {
    long seconds = read32(buffer, offset);
    long fraction = read32(buffer, offset + 4);
    return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);        
}

/**
 * Writes 0 as NTP starttime stamp in the buffer. --> Then NTP returns Time OFFSET since 1900
 */    
private void writeTimeStamp(byte[] buffer, int offset) {        
    int ofs =  offset++;

    for (int i=ofs;i<(ofs+8);i++)
      buffer[i] = (byte)(0);             
}

}

And use it with:

并使用它:

        long now = 0;

        NTP_UTC_Time client = new NTP_UTC_Time();

        if (client.requestTime("pool.ntp.org", 2000)) {              
          now = client.getNtpTime();
        }

If you need UTC Time "now" as DateTimeString use function:

如果您需要UTC时间“现在”作为DateTimeString使用函数:

private String get_UTC_Datetime_from_timestamp(long timeStamp){

    try{

        Calendar cal = Calendar.getInstance();
        TimeZone tz = cal.getTimeZone();

        int tzt = tz.getOffset(System.currentTimeMillis());

        timeStamp -= tzt;

        // DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());
        DateFormat sdf = new SimpleDateFormat();
        Date netDate = (new Date(timeStamp));
        return sdf.format(netDate);
    }
    catch(Exception ex){
        return "";
     }
    } 

and use it with:

并使用它:

String UTC_DateTime = get_UTC_Datetime_from_timestamp(now);

#25


1  

Here is my implementation of toUTC:

以下是我对toUTC的实施:

    public static Date toUTC(Date date){
    long datems = date.getTime();
    long timezoneoffset = TimeZone.getDefault().getOffset(datems);
    datems -= timezoneoffset;
    return new Date(datems);
}

There's probably several ways to improve it, but it works for me.

可能有几种方法可以改进它,但它对我有效。

#26


0  

this is my implementation:

这是我的实现:

public static String GetCurrentTimeStamp()
{
    Calendar cal=Calendar.getInstance();
    long offset = cal.getTimeZone().getOffset(System.currentTimeMillis());//if you want in UTC else remove it .
    return new java.sql.Timestamp(System.currentTimeMillis()+offset).toString();    
}

#27


0  

If you're using joda time and want the current time in milliseconds without your local offset you can use this:

如果你正在使用joda时间,并且希望当前时间在毫秒内没有你的本地偏移量,你可以使用这个:

long instant = DateTimeZone.UTC.getMillisKeepLocal(DateTimeZone.getDefault(), System.currentTimeMillis());

#28


0  

If you want to avoid parsing the date and just want a timestamp in GMT, you could use:

如果你想避免解析日期,只想在格林尼治标准时间戳,你可以使用:

final Date gmt = new Timestamp(System.currentTimeMillis()
            - Calendar.getInstance().getTimeZone()
                    .getOffset(System.currentTimeMillis()));

#1


325  

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。日期没有特定的时区,尽管它的值通常被认为与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.

精确地说:java.util中的值。日期是Unix纪元以来的毫秒数,它发生在1970年1月1日午夜UTC。在其他时区也可以描述相同的时代,但是传统的描述是UTC。因为它是一个固定的纪元以来的几毫秒,java.util中的值。在任何特定的瞬间,世界各地的日期都是相同的,无论当地时区。

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.

我怀疑问题在于,您通过使用本地时区的日历实例来显示它,或者可能使用Date.toString(),它还使用本地时区,或者一个SimpleDateFormat实例,默认情况下,它也使用本地时区。

If this isn't the problem, please post some sample code.

如果这不是问题,请张贴一些示例代码。

I would, however, recommend that you use Joda-Time anyway, which offers a much clearer API.

但是,我建议您使用Joda-Time,它提供了一个更加清晰的API。

#2


241  

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()) );

#3


163  

tl;dr

Instant.now()

Generate a String to represent that value:

生成一个字符串来表示该值:

Instant.now().toString()  

2016-09-13T23:30:52.123Z

2016 - 09 - 13 - t23:30:52.123z

Details

As the correct answer by Jon Skeet stated, a java.util.Date object has no time zone. But its toString implementation applies the JVM’s default time zone when generating the String representation of that date-time value. Confusingly to the naïve programmer, a Date seems to have a time zone but does not.

正如Jon Skeet所指出的正确答案,一个java.util。日期对象没有时区。但是它的toString实现在生成该日期时间值的字符串表示时应用JVM的默认时区。对于天真的程序员来说,一个日期似乎有一个时区,但却没有。

The java.util.Date, j.u.Calendar, and java.text.SimpleDateFormat classes bundled with Java are notoriously troublesome. Avoid them. Instead, use either of these competent date-time libraries:

java.util。日期、j.u。日历和text。与Java绑定的SimpleDateFormat类是出了名的麻烦。避免它们。相反,可以使用这些有能力的日期时间库:

java.time (Java 8)

Java 8 brings an excellent new java.time.* package to supplant the old java.util.Date/Calendar classes.

Java 8带来了一个优秀的新Java .time。包以取代旧的java.util。日期/日历类。

Getting current time in UTC/GMT is a simple one-liner…

在UTC/GMT获得当前时间是一个简单的一行程序…

Instant instant = Instant.now();

That Instant class is the basic building block in java.time, representing a moment on the timeline in UTC with a resolution of nanoseconds.

这个即时类是java中的基本构建块。时间,表示在UTC时间轴上的一个瞬间,它的分辨率为纳秒。

In Java 8, the current moment is captured with only up to milliseconds resolution. Java 9 brings a fresh implementation of Clock captures the current moment in up to the full nanosecond capability of this class, depending on the ability of your host computer’s clock hardware.

在Java 8中,当前的时刻仅以毫秒的分辨率捕获。Java 9带来了一个新实现的时钟捕捉当前时刻,在这类的全部纳秒能力,取决于你的主机的时钟硬件的能力。

It’s toString method generates a String representation of its value using one specific ISO 8601 format. That format outputs zero, three, six or nine digits digits (milliseconds, microseconds, or nanoseconds) as necessary to represent the fraction-of-second.

它的toString方法使用一个特定的ISO 8601格式生成它的值的字符串表示。该格式输出0、3、6或9位数字(毫秒、微秒或纳秒),以表示秒的动作。

If you want more flexible formatting, adjustments in or out of various time zones, or other additional features, then apply a time zone (ZoneId object) to get a ZonedDateTime. The time zone can be for UTC or any other time zone. The subclass of ZoneId, ZoneOffset holds a constant for UTC.

如果您想要更灵活的格式化,可以在不同的时区或其他额外的特性中进行调整,然后应用一个时区(ZoneId对象)来获得一个ZonedDateTime。时区可以是UTC或任何其他时区。ZoneId的子类,ZoneOffset为UTC保留一个常量。

ZonedDateTime now = ZonedDateTime.now( ZoneOffset.UTC );

Dump to console…

转储控制台……

System.out.println( "now: " + now );

When run…

运行时……

now: 2014-01-21T23:42:03.522Z

The java.time classes are defined by JSR 310. They were inspired by Joda-Time but are entirely re-architected.

java。时间类由JSR 310定义。他们受到了joda时间的启发,但完全重新架构了。

Joda-Time

UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

更新:Joda-Time项目,现在在维护模式,建议迁移到java。时间类。

Using the Joda-Time 3rd-party open-source free-of-cost library, you can get the current date-time in just one line of code.

使用Joda-Time第三方开源免费库,您可以在一行代码中获得当前的日期时间。

Joda-Time inspired the new java.time.* classes in Java 8, but has a different architecture. You may use Joda-Time in older versions of Java. Joda-Time continues to work in Java 8 and continues to be actively maintained (as of 2014). However, the Joda-Time team does advise migration to java.time.

新java.time Joda-Time启发。*类在Java 8中,但却具有不同的结构。你可以用Joda-Time旧版本的Java。Joda-Time继续在Java 8工作,继续积极维护(截至2014年)。然而,Joda-Time团队并建议迁移java.time。

System.out.println( "UTC/GMT date-time in ISO 8601 format: " + new org.joda.time.DateTime( org.joda.time.DateTimeZone.UTC ) );

More detailed example code (Joda-Time 2.3)…

更详细的示例代码(Joda-Time 2.3)…

org.joda.time.DateTime now = new org.joda.time.DateTime(); // Default time zone.
org.joda.time.DateTime zulu = now.toDateTime( org.joda.time.DateTimeZone.UTC );

Dump to console…

转储控制台……

System.out.println( "Local time in ISO 8601 format: " + now );
System.out.println( "Same moment in UTC (Zulu): " + zulu );

When run…

运行时……

Local time in ISO 8601 format: 2014-01-21T15:34:29.933-08:00
Same moment in UTC (Zulu): 2014-01-21T23:34:29.933Z

For more example code doing time zone work, see my answer to a similar question.

对于更多的示例代码执行时区工作,请参见我对类似问题的回答。

Time Zone

I recommend you always specify a time zone rather than relying implicitly on the JVM’s current default time zone (which can change at any moment!). Such reliance seems to be a common cause of confusion and bugs in date-time work.

我建议您总是指定一个时区,而不是隐式地依赖JVM的当前默认时区(随时可以更改!)这种依赖似乎是在时间工作中造成混乱和错误的常见原因。

When calling now() pass the desired/expected time zone to be assigned. Use the DateTimeZone class.

当调用now()时,传递所需的/预期的时区。使用DateTimeZone时区类。

DateTimeZone zoneMontréal = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zoneMontréal );

That class holds a constant for UTC time zone.

这个类对UTC时区保持不变。

DateTime now = DateTime.now( DateTimeZone.UTC );

If you truly want to use the JVM’s current default time zone, make an explicit call so your code is self-documenting.

如果您确实想要使用JVM的当前默认时区,那么就进行显式调用,这样您的代码就可以自我记录了。

DateTimeZone zoneDefault = DateTimeZone.getDefault();

ISO 8601

Read about ISO 8601 formats. Both java.time and Joda-Time use that standard’s sensible formats as their defaults for both parsing and generating strings.

读到ISO 8601格式。java。时间和Joda-Time使用标准的合理的格式解析和生成字符串作为其默认值。


Actually, java.util.Date does have a time zone, buried deep under layers of source code. For most practical purposes, that time zone is ignored. So, as shorthand, we say java.util.Date has no time zone. Furthermore, that buried time zone is not the one used by Date’s toString method; that method uses the JVM’s current default time zone. All the more reason to avoid this confusing class and stick with Joda-Time and java.time.

†实际上,java.util。日期有一个时区,深埋层的源代码。对于大多数实用目的,时区被忽略。所以,作为速记,我们说java.util。日期没有时区。此外,埋时区不使用的一个约会对象的toString方法;该方法使用JVM当前的默认时区。更有理由避免这种混淆类和坚持Joda-Time java.time。

#4


73  

This definitely returns UTC time: as String and Date objects !

这个肯定返回UTC时间:字符串和约会对象!

static final String DATEFORMAT = "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(DATEFORMAT);
    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;
}

#5


65  

    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());

#6


48  

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.

地球上任何地方的时间都是相同的,但我们对时间的感知可能会因地点不同而有所不同。

#7


15  

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(格林尼治时间));然后使用aGMTCalendar对象执行的所有操作将完成了时区和格林尼治时间没有日光节约时间或固定补偿

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.

#8


12  

This works for getting UTC milliseconds in Android.

这适用于在Android上获得UTC毫秒。

Calendar c = Calendar.getInstance();
int utcOffset = c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET);  
Long utcMilliseconds = c.getTimeInMillis() + utcOffset;

#9


12  

This code prints the current time UTC.

此代码打印当前UTC时间。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;


public class Test
{
    public static void main(final String[] args) throws ParseException
    {
        final SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
        f.setTimeZone(TimeZone.getTimeZone("UTC"));
        System.out.println(f.format(new Date()));
    }
}

Result

结果

2013-10-26 14:37:48 UTC

#10


9  

Jon Skeet asks:

Jon水瓢问道:

@Downvoter: Care to comment? What exactly is incorrect in my answer? – Jon Skeet Oct 26 '09 at 21:09

@Downvoter:想发表意见吗?我的回答到底有什么错误?- Jon Skeet 2009年10月26日21:09。

I am not the Downvoter, but here is what seems to be incorrect in that answer. You said:

我不是消极的选民,但在这个问题上,这似乎是不正确的。你说:

java.util.Date is always in UTC. What makes you think it's in local time? 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.

java.util。日期总是在UTC。是什么让你认为是在当地时间?我怀疑问题是您通过使用本地时区的日历实例来显示它,或者可能使用Date.toString(),它也使用本地时区。

However, the code:

然而,代码:

System.out.println(new java.util.Date().getHours() + " hours");

gives the local hours, not GMT (UTC hours), using no Calendar and no SimpleDateFormat at all.

提供本地时间,而不是GMT (UTC小时),没有使用日历,也没有SimpleDateFormat。

That is why is seems something is incorrect.

这就是为什么有些事情似乎是不正确的。

Putting together the responses, the code:

把这些回应,代码:

System.out.println(Calendar.getInstance(TimeZone.getTimeZone("GMT"))
                           .get(Calendar.HOUR_OF_DAY) + " Hours");

shows the GMT hours instead of the local hours -- note that getTime.getHours() is missing because that would create a Date() object, which theoretically stores the date in GMT, but gives back the hours in the local time zone.

显示的是GMT时间,而不是本地时间——请注意getTime.getHours()丢失了,因为它将创建一个Date()对象,该对象理论上存储了GMT的日期,但是返回了本地时区的时间。

#11


7  

If you want a Date object with fields adjusted for UTC you can do it like this with Joda Time:

如果你想要一个与UTC相适应的日期对象,你可以用Joda时间来这样做:

import org.joda.time.DateTimeZone;
import java.util.Date;

...

Date local = new Date();
System.out.println("Local: " + local);
DateTimeZone zone = DateTimeZone.getDefault();
long utc = zone.convertLocalToUTC(local.getTime(), false);
System.out.println("UTC: " + new Date(utc));

#12


6  

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时区完成,并且不会使用夏令时或固定的偏移量。我认为前面的海报是正确的,日期()对象总是返回一个GMT常量,直到你去做一些与日期对象相关的事情,它才会被转换到本地时区。

#13


6  

SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormatGmt.format(date));

#14


5  

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中不推荐日期和时间戳。它不是日历类。

#15


5  

Here an other suggestion to get a GMT Timestamp object:

这里还有一个建议,可以得到一个GMT时间戳对象:

import java.sql.Timestamp;
import java.util.Calendar;

...

private static Timestamp getGMT() {
   Calendar cal = Calendar.getInstance();
   return new Timestamp(cal.getTimeInMillis()
                       -cal.get(Calendar.ZONE_OFFSET)
                       -cal.get(Calendar.DST_OFFSET));
}

#16


5  

Here is another way to get GMT time in String format

这里还有另一种方法,以字符串格式获取GMT时间。

String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z" ;
final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String dateTimeString =  sdf.format(new Date());

#17


5  

You can directly use this

你可以直接用这个。

SimpleDateFormat dateFormatGmt = new SimpleDateFormat("dd:MM:yyyy HH:mm:ss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormatGmt.format(new Date())+"");

#18


4  

Just to make this simpler, to create a Date in UTC you can use Calendar :

为了让这个更简单,在UTC中创建一个日期,你可以使用日历:

Calendar.getInstance(TimeZone.getTimeZone("UTC"));

Which will construct a new instance for Calendar using the "UTC" TimeZone.

它将使用“UTC”时区构造一个新的日历实例。

If you need a Date object from that calendar you could just use getTime().

如果您需要从该日历上的日期对象,您可以使用getTime()。

#19


3  

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

#20


3  

Converting Current DateTime in UTC:

在UTC中转换当前的DateTime:

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

DateTimeZone dateTimeZone = DateTimeZone.getDefault(); //Default Time Zone

DateTime currDateTime = new DateTime(); //Current DateTime

long utcTime = dateTimeZone.convertLocalToUTC(currDateTime .getMillis(), false);

String currTime = formatter.print(utcTime); //UTC time converted to string from long in format of formatter

currDateTime = formatter.parseDateTime(currTime); //Converted to DateTime in UTC

#21


2  

This worked for me, returns the timestamp in GMT!

这对我起作用了,在GMT时返回时间戳!

    Date currDate;
    SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
    dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
    SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");

    long currTime = 0;
    try {

        currDate = dateFormatLocal.parse( dateFormatGmt.format(new Date()) );
        currTime = currDate.getTime();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

#22


2  

public static void main(String args[]){
    LocalDate date=LocalDate.now();  
    System.out.println("Current date = "+date);
}

#23


1  

To put it simple. A calendar object stores information about time zone but when you perform cal.getTime() then the timezone information will be lost. So for Timezone conversions I will advice to use DateFormat classes...

把它简单。日历对象存储关于时区的信息,但是当您执行cal.getTime()时,时区信息就会丢失。因此,对于时区转换,我将建议使用DateFormat类…

#24


1  

Use this Class to get ever the right UTC Time from a Online NTP Server:

使用这个类从一个在线的NTP服务器获得正确的UTC时间:

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


class NTP_UTC_Time
{
private static final String TAG = "SntpClient";

private static final int RECEIVE_TIME_OFFSET = 32;
private static final int TRANSMIT_TIME_OFFSET = 40;
private static final int NTP_PACKET_SIZE = 48;

private static final int NTP_PORT = 123;
private static final int NTP_MODE_CLIENT = 3;
private static final int NTP_VERSION = 3;

// Number of seconds between Jan 1, 1900 and Jan 1, 1970
// 70 years plus 17 leap days
private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;

private long mNtpTime;

public boolean requestTime(String host, int timeout) {
    try {
        DatagramSocket socket = new DatagramSocket();
        socket.setSoTimeout(timeout);
        InetAddress address = InetAddress.getByName(host);
        byte[] buffer = new byte[NTP_PACKET_SIZE];
        DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);

        buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);

        writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET);

        socket.send(request);

        // read the response
        DatagramPacket response = new DatagramPacket(buffer, buffer.length);
        socket.receive(response);          
        socket.close();

        mNtpTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);            
    } catch (Exception e) {
      //  if (Config.LOGD) Log.d(TAG, "request time failed: " + e);
        return false;
    }

    return true;
}


public long getNtpTime() {
    return mNtpTime;
}


/**
 * Reads an unsigned 32 bit big endian number from the given offset in the buffer.
 */
private long read32(byte[] buffer, int offset) {
    byte b0 = buffer[offset];
    byte b1 = buffer[offset+1];
    byte b2 = buffer[offset+2];
    byte b3 = buffer[offset+3];

    // convert signed bytes to unsigned values
    int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
    int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
    int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
    int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);

    return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
}

/**
 * Reads the NTP time stamp at the given offset in the buffer and returns 
 * it as a system time (milliseconds since January 1, 1970).
 */    
private long readTimeStamp(byte[] buffer, int offset) {
    long seconds = read32(buffer, offset);
    long fraction = read32(buffer, offset + 4);
    return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);        
}

/**
 * Writes 0 as NTP starttime stamp in the buffer. --> Then NTP returns Time OFFSET since 1900
 */    
private void writeTimeStamp(byte[] buffer, int offset) {        
    int ofs =  offset++;

    for (int i=ofs;i<(ofs+8);i++)
      buffer[i] = (byte)(0);             
}

}

And use it with:

并使用它:

        long now = 0;

        NTP_UTC_Time client = new NTP_UTC_Time();

        if (client.requestTime("pool.ntp.org", 2000)) {              
          now = client.getNtpTime();
        }

If you need UTC Time "now" as DateTimeString use function:

如果您需要UTC时间“现在”作为DateTimeString使用函数:

private String get_UTC_Datetime_from_timestamp(long timeStamp){

    try{

        Calendar cal = Calendar.getInstance();
        TimeZone tz = cal.getTimeZone();

        int tzt = tz.getOffset(System.currentTimeMillis());

        timeStamp -= tzt;

        // DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());
        DateFormat sdf = new SimpleDateFormat();
        Date netDate = (new Date(timeStamp));
        return sdf.format(netDate);
    }
    catch(Exception ex){
        return "";
     }
    } 

and use it with:

并使用它:

String UTC_DateTime = get_UTC_Datetime_from_timestamp(now);

#25


1  

Here is my implementation of toUTC:

以下是我对toUTC的实施:

    public static Date toUTC(Date date){
    long datems = date.getTime();
    long timezoneoffset = TimeZone.getDefault().getOffset(datems);
    datems -= timezoneoffset;
    return new Date(datems);
}

There's probably several ways to improve it, but it works for me.

可能有几种方法可以改进它,但它对我有效。

#26


0  

this is my implementation:

这是我的实现:

public static String GetCurrentTimeStamp()
{
    Calendar cal=Calendar.getInstance();
    long offset = cal.getTimeZone().getOffset(System.currentTimeMillis());//if you want in UTC else remove it .
    return new java.sql.Timestamp(System.currentTimeMillis()+offset).toString();    
}

#27


0  

If you're using joda time and want the current time in milliseconds without your local offset you can use this:

如果你正在使用joda时间,并且希望当前时间在毫秒内没有你的本地偏移量,你可以使用这个:

long instant = DateTimeZone.UTC.getMillisKeepLocal(DateTimeZone.getDefault(), System.currentTimeMillis());

#28


0  

If you want to avoid parsing the date and just want a timestamp in GMT, you could use:

如果你想避免解析日期,只想在格林尼治标准时间戳,你可以使用:

final Date gmt = new Timestamp(System.currentTimeMillis()
            - Calendar.getInstance().getTimeZone()
                    .getOffset(System.currentTimeMillis()));