在android中从互联网获取当前日期

Pun*_*r90 1 datetime android date android-asynctask

我想知道 android 中是否有任何 API/类可以为我们提供原始日期,因为我不想从 android 设备获取日期/时间。

Met*_*ete 5

更新!!

旧答案不起作用,因为 timeapi.org 已关闭。

这是我的新 getTime 方法。它正在使用JSOUP

private long getTime() throws Exception {
    String url = "https://time.is/Unix_time_now";
    Document doc = Jsoup.parse(new URL(url).openStream(), "UTF-8", url);
    String[] tags = new String[] {
            "div[id=time_section]",
            "div[id=clock0_bg]"
    };
    Elements elements= doc.select(tags[0]);
    for (int i = 0; i <tags.length; i++) {
        elements = elements.select(tags[i]);
    }
    return Long.parseLong(elements.text());
}
Run Code Online (Sandbox Code Playgroud)

将时间戳转换为可读的日期和时间

private String getDate(long time) {
    Calendar cal = Calendar.getInstance(Locale.ENGLISH);
    cal.setTimeInMillis(time * 1000);
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm a", Locale.ENGLISH);
    
    return dateFormat.format(cal.getTime());
} 
Run Code Online (Sandbox Code Playgroud)

摇篮:

implementation 'org.jsoup:jsoup:1.10.2'
Run Code Online (Sandbox Code Playgroud)