gpt4 book ai didi

android - 如何在 Android 中在线获取当前 UTC 时间?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:28:11 25 4
gpt4 key购买 nike

我在我的应用程序中使用 UTC 时区和时间来获取数据。在应用程序中,用户可以在任何地方获取 UTC 时间并用于获取数据。我用这个方法来获取UTC时间。

String format = "yyyy-MM-dd HH:mm:ss";
final SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String utcTime = sdf.format(new Date());

应用程序运行良好。但它正在将系统时间转换为 UTC 时间。问题是有时用户可以将时间更改为错误的时间。所以数据没有来。

上述问题的案例是:

例如,印度的当前日期时间是 2012 年 7 月 26 日星期四 14:27:56,时区加尔各答。那么时间,太平洋时区,应该是星期四,26 July 2012, 01:59:30 PDT。

但是用户将他的设备时间从 14:27:56 更改为 13:27:56,因此转换后的 UTC 时间将为 2012 年 7 月 26 日星期四 00:59:30 PDT。由于一小时的差异,此时我的应用程序无法获取日期。

我不想使用 Java 的日期、日历类,也不想使用设备时间。如何直接获取UTC时间,而不涉及设备的时间、日期。是否有任何开源 API?

提前致谢。

最佳答案

如果系统时间发生变化,则上述 SntpClient 上的 UTC 时间将不起作用,例如手动8小时。因为它使用 System.currentTimeMillis 返回错误值!!!

        // get current time and write it to the request packet
long requestTime = System.currentTimeMillis();
long requestTicks = SystemClock.elapsedRealtime();

最好使用此类从 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);
}

}

并将其用于:

        long now = 0;

NTP_UTC_Time client = new NTP_UTC_Time();

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

如果您需要“现在”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 "";
}
}

并将其用于:

String UTC_DateTime = get_UTC_Datetime_from_timestamp(now);

关于android - 如何在 Android 中在线获取当前 UTC 时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11665923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com